JS singleton design pattern, the combined mode, the observer pattern, strategy pattern

About JS is 设计模式与单例模式presented on a blog made the introduction, as detailed: JS design patterns and single-case model


Well, here I will combine some instances, that my understanding of the patterns and combinations of the observer pattern:

1, combined mode:

  • Combination patterns are formed between the object 树形structure;
  • And a combination mode basic object composite objects 被一致对待;
  • Without concern for objects have many layers, just when you call 根部进行调用;
  • A plurality of functional objects, are assembled to achieve 批量执行;

Imagine that we now have got a universal remote control, when we go home, press the switch, the following things will be executed:

  • Home, open the door
  • Open the computer
  • Open Music
// 先准备一些需要批量执行的功能
class GoHome{
    init(){
        console.log("到家了,开门");
    }
}
class OpenComputer{
    init(){
        console.log("开电脑");
    }
}
class OpenMusic{
    init(){
        console.log("开音乐");
    }
}

// 组合器,用来组合功能
class Comb{
    constructor(){
        // 准备容器,用来防止将来组合起来的功能
        this.skills = [];
    }
    // 用来组合的功能,接收要组合的对象
    add(task){
        // 向容器中填入,将来准备批量使用的对象
        this.skills.push(task);
    }
    // 用来批量执行的功能
    action(){
        // 拿到容器中所有的对象,才能批量执行
        this.skills.forEach( val => {
            val.init();
        } );
    }
}

// 创建一个组合器
var c = new Comb();

// 提前将,将来要批量操作的对象,组合起来
c.add( new GoHome() );
c.add( new OpenComputer() );
c.add( new OpenMusic() );

// 等待何时的时机,执行组合器的启动功能
c.action();
    // 在内部,会自动执行所有已经组合起来的对象的功能

Thus, we can summarize 组合模式的特点:

1.批量执行
2.启动一个方法,会遍历多个方法,同时执行,有点类似于递归的感觉
3.组合模式略微耗性能,但是执行方便
 目前只是一个基础组合。
 高级组合:
1.组合成树状结构,每个对象下,还会有自己的子对象
2.如果执行了父对象的某个方法,所有的子对象会跟随执行
3.组合模式一般建议使用在动态的html结构上,因为组合模式的结构和html的结构,出奇的一致
4.基本对象和组合对象被一致对待, 所以要保证基本对象(叶对象)和组合对象具有一致方法

2, observer mode:

  • The observer pattern is also called also called Observer mode, publish / subscribe model, also proposed by the GoF 23种软件设计模式的一种.
  • Mode observer 行为模式之一, it 作用is when the state of an object is changed, it is possible to automatically notify other related objects, the automatic refresh state of the object or process (theme data change, notify other individuals performing the corresponding object, and make the appropriate Data Update).
  • This design model can be greatly 降低between the program modules 耦合度to facilitate 更加灵活the maintenance and extension.
  • To 观察的角度find the corresponding situation, deal with the problem.
  • The observer pattern contains two roles:
    观察者(订阅者): will update their information or status (subscribers can join or leave at any time);
    被观察者(发布者): receiving the information released by the publisher, in order to make corresponding changes or execution.
  • Easily achieve a simple broadcast communication, to achieve 一对多the correspondence relationship.
  • 核心思想: As long as the viewer is subscribed to the event observer, so when changing the state of the observer, is the observer will take the initiative to inform the viewer, without concern for what to do after the event to get the viewer, the actual procedure may be execution subscribers callback function.
  • Implemented in a Javascript example:
// 我们向某dom文档订阅了点击事件,当点击发生时,他会执行我们传入的callback
element.addEventListener("click", callback, false)
element.addEventListener("click", callback, false)
  • Simple example:
// 模拟事件监听式处理事件的过程
// 需要一个观察者(班主任),创建一个事件容器(小本本),并准备on等方法(如何操作小本本)...
function Observer(){
this.msg = {};
}
// 向小本本中添加事件,消息
Observer.prototype.on = function(type, cb){
// 判断小本本中,有没有当前传进来的这个类型
// 如何没有,走else
if(this.msg[type]){
    // 如果有,直接给第一次设置的这个数组,添加个新数据
    this.msg[type].push(cb);
}else{
    // 给他设置一个对应的属性,同时,属性值需要提前写成数组
    this.msg[type] = [cb];
}
}
Observer.prototype.emit = function(type){
// 首先判断小本本中是不是已经记录
if(this.msg[type]){
    var event = {
        type:type
    }
    // 如果已经记录了信息,那么就去执行这个消息对应的所有的处理函数
    this.msg[type].forEach(val=>{
        val.call(this,event);
    })
}
}
Observer.prototype.off = function(type, cb){
// 首先判断小本本中是不是已经记录
if(this.msg[type]){
    // 准备保存符合传参的处理函数的索引
    var i = 0;
    // 遍历,判断,当前类型对应的每一个处理函数,依次作比较
    var onoff = this.msg[type].some((val, idx)=>{
        i = idx;
        return val === cb;
    })
    // 判断是否获取到重复的函数
    if(onoff){
        // 如果有,那么就在当前的消息处理函数的队列中,删除这个函数
        this.msg[type].splice(i, 1);
    }
}
}

// 首先创建一个观察者对象
var ob = new Observer();
// 准备两个处理函数
function a(){
console.log("找来谈话");
console.log(this);
}
function b(){
console.log("叫来家长");
}

// 随便绑定一个消息,给了两个处理函数
ob.on("早恋",a);
ob.on("早恋",b);

// 模拟事件的执行
ob.emit("早恋");

// 删除一个处理函数
ob.off("早恋", b);

// 模拟事件的执行
ob.emit("早恋");

var obj = {
    data: {
    list: []
      },
 }
 // defineProperty 可以观察 obj对象 的list 属性的使用
  Object.defineProperty(obj, 'list', {
       get() {
          console.log('获取了list 属性');
          console.log(this.data['list']);
          return this.data['list'];
      },
   		set(val) {
                console.log('值被更改了')this.data['list'] = val;
        }
   })
// 获取了list属性,那么get 方法就会被调用
console.log(obj.list);
// 设置了list属性set 方法就会被调用
obj.list = ['a', 'b'];

Note: the contents of memory observer mode, you need to perform in the message box; on the method, adding the operation to be performed; emit, release to perform operations; off, delete operations performed.

3, Strategy Mode:

Define a policy mode: Define a family of algorithms, encapsulate each one them, and make them interchangeable. That is: given multiple plans, when a certain state occurring in the future, the implementation of the corresponding program.

  • Strategy mode 目的is to implement the algorithm in use of separate.
  • A program mode of policy-based 至少由两部分composition.
    The first part is a set of policy class (variable), the policy class encapsulates a specific algorithm, and for a specific calculation.
    The second part is the Environmental Context (unchanged), Context accept the client's request, then the request will be entrusted to an policy class. To do this, explain Context in order to maintain a reference to a policy object.
  • Simple example:
/*策略类*/
var test = {
    "A": function (money) {
        return money + 6;
    },
    "B": function (money) {
        return money + 4;
    },
    "C": function (money) {
        return money + 2;
    }
};
/*环境类*/
var calculateBouns = function (level, money) {
    return test[level](money);
};
console.log(calculateBouns('A', 6)); // 12
console.log(calculateBouns('B', 6)); // 10
console.log(calculateBouns('C', 6)); // 8

Strategy Mode advantages:

  • Policy model is a full package of objects of various algorithms, these algorithms can be used for a variety of objects, it can be supplied to any condition determination.
  • Strategy pattern using a combination of commission and polymorphic techniques and ideas, can effectively avoid multiple conditions select statement that strategy pattern can avoid a lot if conditional statement.
  • Strategy pattern conforms to the Open - Closed Principle, to make the code easier to understand and extend.
  • Strategy mode code can be reused.
Published 75 original articles · won praise 304 · views 60000 +

Guess you like

Origin blog.csdn.net/weixin_42881768/article/details/104930993