Object-oriented implementation of observer mode with javascript

Define a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated.
applicability

    1. When an abstract model has two aspects, one aspect depends on the other.
      Encapsulate the two into independent objects so that they can be changed and reused independently.

    2. When a change to an object needs to change other objects at the same time, I don't know how many objects need to be changed.

    3. When an object must notify other objects, and it cannot assume who the other objects are.
            
Participant

    1. Subject (target) The
      target knows its observers. There can be any number of observers observing the same target.
      Provides an interface for registering and deleting observer objects.

    2. Observer (observer)
      defines an update interface for those objects that need to be notified when the target changes.

    3. ConcreteSubject (specific target)
      saves the relevant state into each ConcreteObserver object.
      When its state changes, it sends a notification to its various observers.

    4. ConcreteObserver (specific observer)
      maintains a reference to the ConcreteSubject object.
      Store related states, which should be consistent with the state of the target.
      Implement the update interface of Observer to keep its own state consistent with the state of the target

 

Demand scenario: Simulate to realize that users subscribe to CCTV and the news consulting of the Ministry of National Defense newspaper. As users subscribe to newspapers, all objects that rely on newspapers to generate news will change with the subscription information.

Key code

function BusinessOne(name){
	this.name = name;
	//订阅者的集合
	this.subscribers = new Array();
}
//订阅者的发送消息的方法(推模式)
BusinessOne.prototype.delive = function(news){
	var self = this;
	//给每一个订阅者发送消息
	this.subscribers.forEach(
		function(fn){
			//调用接受者处理信息的函数
			fn(news,self);
		}
	)
}
//扩展公共订阅的函数,和取消订阅的函数
Function.prototype.subscribe = function(publisher){
	var that = this;
	//some 访问数组度i型并且以参数的形式传回回调函数中
	//只要至少有一次返回是true那么some就是true
	var alreadyExists = publisher.subscribers.some(
		function(el){
			//处理不能重复订阅的功能
			if(el == that){
				return;
			}
		}
	);
	//没用订阅你就可以订阅
	if(!alreadyExists){
		publisher.subscribers.push(that);
	}
	return this;
}
//取消
Function.prototype.unsubscribe = function(publisher){
	var that = this;
	publisher.subscribers = publisher.subscribers.filter(
		function(el){
			if(el !== that){
				return el;
			}
		}
	);
	return this;
};

 

 

Complete javascript code implementation: https://github.com/sunjdk/learnvue/tree/master/doc/observer-subscriber model

 

Guess you like

Origin blog.csdn.net/taotaobaobei/article/details/112189421