TS中使用单例模式实例对象,及存取值

单例模式实例对象优点:可以保证实例对象的唯一性,及数据的正确性


示例代码:
model层(数据层)

//VipVo.ts:
class VipVo{
     /** VIP等级 */       
    public vip:number;
}

//VipMode.ts:
class VipModel{
      private static _instance:VipModel;
      private _vipVo:VipVo;
      constructor(){
        super();
      }
      public static getInstance():VipModel{
           if(this._instance == null){
            this._instance = new VipModel();
        }
        return this._instance;
     }
     public get vipVo():VipVo{
        return this._vipVo;
     }
     public setVipVo(vo:VipVo):void{
        this._vipVo = vo;
     }
}

controller层(控制层)

//ImitVipMgr.ts
class ImitVipMgr {
        //模拟的vip等级
        private static vipLevel:number=2;
        constructor() {
            super();
        }
        private static _instance: ImitVipMgr;
        public static getInstance(): ImitVipMgr {
          if (this._instance == null) {
            this._instance = new  ImitVipMgr();
          }
          return this._instance;
        }
        public static setVip():void{
              var vipVo: VipVo = new VipVo();
              vipVo.vip = this.vipLevel++;
              //实例VipModel对象,存值
              VipModel.getInstance().setVipVo(vipVo);
        }
}

view层(视图层)

//第一步:实例ImitVipMgr对象,存值
var imitVipMgr:ImitVipMgr=ImitVipMgr.getInstance();
imitVipMgr.setVip();

//第二步:实例VipModel对象,取值
var vipMode:VipModel = VipModel.getInstance();
console.log(vipMode.vipVo.vip);
//输出2

注意:
单例模式实例对象代码

public static getInstance():VipModel{
       if(this._instance == null){
            this._instance = new VipModel();
        }
        return this._instance;
 }

获取对象代码:

var vipMode:VipModel = VipModel.getInstance();

如果获取对象的时候,使用了new,比如:

var vipMode:VipModel =new  VipModel();
console.log(vipMode.vipVo.vip);
//输出undefined

因为new一个实例,相当于创建一块内存,与之前的对象不是同一个对象,所以属性不存在
故,使用单例模式是保证对象唯一性和数据正确性的方法

你可能感兴趣的:(TS中使用单例模式实例对象,及存取值)