zoukankan      html  css  js  c++  java
  • js设计模式

    单例模式

    (单体模式提供了一种将代码组织为一个逻辑单元的手段,这个逻辑单元中的代码可以通过单一变量进行访问)

    let obj = {
      name: 'xx',
      age: 20
    }

    工厂模式

    (工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式,就是同样形式参数返回不同的实例)

    function Person() { this.name = 'Person1'; }
    function Animal() { this.name = 'Animal1'; }
    
    function Factory() {}
    Factory.prototype.getInstance = function(className) {
      return eval('new ' + className + '()');
    }
    
    var factory = new Factory();
    var obj1 = factory.getInstance('Person');
    var obj2 = factory.getInstance('Animal');
    console.log(obj1.name); // Person1
    console.log(obj2.name); // Animal1

    代理模式

    (为其他对象提供一种代理以控制对这个对象的访问)

    function Person() { }
    Person.prototype.sayName = function() { console.log('michaelqin'); }
    Person.prototype.sayAge = function() { console.log(30); }
    
    function PersonProxy() { 
      this.person = new Person();
      const that = this;
      this.callMethod = function(functionName) {
        console.log('before proxy:', functionName);
        that.person[functionName](); // 代理
        console.log('after proxy:', functionName);
      }
    }
    
    var pp = new PersonProxy();
    pp.callMethod('sayName'); // 代理调用Person的方法sayName()
    pp.callMethod('sayAge'); // 代理调用Person的方法sayAge()    

    观察者模式

    function Publisher() {
      this.listeners = [];
    }
    Publisher.prototype = {
      addListener(listener){
        this.listeners.push(listener);
      },
      removeListener(listener){
        delete this.listeners[listener];
      },
      notify(obj){
        this.listeners.forEach(listener => {
          if(typeof listener !== 'undefined'){
            listener.process(obj);
          }
        })
      }
    }
    function Subscriber() {
      
    }
    Subscriber.prototype = {
      process(obj){
        console.log(obj)
      }
    }
    
    const p = new Publisher();
  • 相关阅读:
    <转> 百度空间 最大子图形问题详解
    Hdu 1124 Factorial
    Uva 457 Linear Cellular Automata
    求01矩阵中的最大的正方形面积
    【HYSBZ】1036 树的统计Count
    【SPOJ】375 Query on a tree
    【POJ】3580 SuperMemo
    【CodeForces】191C Fools and Roads
    【FOJ】2082 过路费
    【HDU】3726 Graph and Queries
  • 原文地址:https://www.cnblogs.com/colima/p/8687123.html
Copyright © 2011-2022 走看看