Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

设计模式 #16

Open
nianxiongdi opened this issue Oct 5, 2019 · 0 comments
Open

设计模式 #16

nianxiongdi opened this issue Oct 5, 2019 · 0 comments

Comments

@nianxiongdi
Copy link
Owner

nianxiongdi commented Oct 5, 2019

单例模式

  • 只能创建一个实例

实例1:

    function A(name){
	    // 如果已存在对应的实例
	   if(typeof A.instance === 'object'){
	       return A.instance
	   }
	   //否则正常创建实例
	   this.name = name
	    
	   // 缓存
	   A.instance =this
	   return this
	}
	var a1 = new A()
	var a2= new A()
	console.log(a1 === a2)//true

例子2:

	class Storage {
        constructor(name) {
            this.instance = null;
        }
        static getInstance(){
            if(!this.instance) {
                this.instance = new Storage();
            }
            return this.instance;       
        }
        setItem = (key, value) => localStorage.setItem(key, value);
        getItem = key => localStorage.getItem(key)
    }
    
    const storage = Storage.getInstance();
    console.log(storage == storage1);

观察者模式

  • 有目标和观察者
  • 观察者注册到目标中,当目标发生变化时,通知观察者.

image

// 观察者列表
function ObserverList () {
    this.observerList = [];
}

ObserverList.prototype.add = function (obj) {
    return this.observerList.push(obj);
}

ObserverList.prototype.count = function () {
    return this.observerList.length;
}

ObserverList.prototype.get = function (index) {
    if (index > -1 && index < this.observerList.length) {
        return this.observerList[index];
    }
}
ObserverList.prototype.indexOf = function (obj, startIndex) {
    var i = startIndex || 0;
    while (i < this.observerList.length) {
        if (this.observerList[i] === obj) {
            return i;
        }
        i++;
    }
    return -1;
}

ObserverList.prototype.removeAt = function (index) {
    this.observerList.splice(index, 1);
}

// 目标
function Subject () {
    this.observers = new ObserverList();
}

Subject.prototype.addObsever = function (observer) {
    this.observers.add(observer);
}

Subject.prototype.removeObsever = function (observer) {
    this.observers.removeAt(this.observers.indexOf(observer, 0));
}

Subject.prototype.notify = function (context) {
    var observerCount = this.observers.count();
    for(var i = 0; i < observerCount; i++) {
        this.observers.get(i).update(context);
    }
}

// 观察者
function Observer () {
    this.update = function (context) {
        console.log(context);
    }
}

var mySubject = new Subject();
mySubject.addObsever(new Observer);
mySubject.notify("hello world");

简化版

// 观察者列表
function ObserverList () {
    this.observerList = [];
}

ObserverList.prototype.add = function (obj) {
    return this.observerList.push(obj);
}

ObserverList.prototype.count = function () {
    return this.observerList.length;
}

ObserverList.prototype.get = function (index) {
    if (index > -1 && index < this.observerList.length) {
        return this.observerList[index];
    }
}
 
// 目标
function Subject () {
    this.observers = new ObserverList();
}

Subject.prototype.addObsever = function (observer) {
    this.observers.add(observer);
}

Subject.prototype.notify = function (context) {
    var observerCount = this.observers.count();
    for(var i = 0; i < observerCount; i++) {
        this.observers.get(i).update(context);
    }
}

// 观察者
function Observer () {
    this.update = function (context) {
        console.log(context);
    }
}

var mySubject = new Subject();
mySubject.addObsever(new Observer);
mySubject.addObsever(new Observer);

mySubject.notify("hello world");

简化版

 
// 目标
function Subject () {
    this.observers = [];
}

Subject.prototype.addObsever = function (observer) {
    this.observers.push(observer); // 观察者列表
}

Subject.prototype.notify = function (context) {
    var observerCount = this.observers.length;
    for(var i = 0; i < observerCount; i++) {
        this.observers[i].update(context);
    }
}

// 观察者
function Observer () {
    this.update = function (context) {
        console.log(context);
    }
}

var mySubject = new Subject();
mySubject.addObsever(new Observer);
mySubject.addObsever(new Observer);

mySubject.notify("hello world");

发布与订阅

  • 发布者把自己想订阅的时间注册到调度中心,当事件触发时,发布者可以把事件发布到调度中心,由调度中心统一调度订阅者注册到调度中心的代码处理.
  • 订阅 <--> 调度中心 <--> 发布者

image

// 发布、订阅模式

var pubsub = {};

(function (myObject){
    var topics = {};

    var subUid = -1;

    // 发布指定订阅
    myObject.publish = function (topic, args) {
        if (!topics[topic]) {
            return false;
        }

        var subscribers = topics[topic];
        var len = subscribers ? subscribers.length : 0;
        while(len--) {
            subscribers[len].func(topic, args);
        }
        return this;
    }

    // 向订阅中心添加订阅
    myObject.subscribe = function (topic, func) {
        if (!topics[topic]) {
            topics[topic] = [];
        }
        var token = (++subUid).toString();
        topics[topic].push({
            token: token,
            func: func
        })
        return token;
    }

    // 向订阅中移除订阅
    myObject.unSubscribe = function (token) {
        for (var m in topics) {
            if (topics[m]) {
                for (var i = 0, j = topics[m].length; i < j; i++) {
                    if (topics[m][i].token === token) {
                        topics[m].splice(i, 1);
                        return token;
                    }
                }
            }
        }
        return this;
    };
})(pubsub);

pubsub.subscribe("test", ()=>{console.log("hello world")});
pubsub.publish("test");

简化版

var pubsub = {};
var topics = {};
 
// 发布指定订阅
pubsub.publish = function (topic, args) {
    if (!topics[topic]) {
        return false;
    }

    var subscribers = topics[topic];
    var len = subscribers ? subscribers.length : 0;
    while(len--) {
        subscribers[len].func(args);
    }
    return this;
}

// 向订阅中心添加订阅
pubsub.subscribe = function (topic, func) {
    if (!topics[topic]) {
        topics[topic] = [];
    }

    topics[topic].push({
        func: func
    })
}
 
pubsub.subscribe("test", (res)=>{console.log(res)});
pubsub.subscribe("test", (res)=>{console.log(res)});

pubsub.publish("test", 'message');

参考

发布与订阅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant