23 kinds of design patterns: Observer Pattern

Definition: between subject an define many dependencies, so that changes state when each object, all objects that depend on it will automatically be notified and updated.

Type: class behavior patterns (also known releases - Subscribe (Publish / Subscribe) mode)

Class Diagram:

        Often, there is a demand in the software system: If the state of an object is changed, some of the objects associated with it will have to make the appropriate changes. For example, we want to design a functional right-click menu, just click the right mouse button in the active areas of the software will pop up a menu; another example, we want to design an automated deployment features, like when the eclipse development, as long as the modified files , eclipse will automatically deploy the modified files to the server. These two features have a similar place, that is listening for an object to another object, as long as it's a state change occurs, will have to make their own appropriate action. In fact, it is possible to achieve this program a lot, but, no doubt using the Observer pattern is a mainstream choice.

Structure observer pattern

In the most basic mode observer, including the following four roles:

  • The observer is: As can be seen in FIG class, class has a storage container for a viewer object Vector (Vector reason to use without the use of List, because the multi-threaded operation, the Vector is safe, and the List is insecure), this is the core of the observer Vector container class, there are three additional methods: attach an object to the observer is to add the container; the detach the object is to remove the viewer from the container; Notify method It is to call the corresponding method observer object in turn. This role can be an interface, it can be abstract or concrete classes, because in many cases will not mix with other modes, so the use of abstract classes more.
  • Observer: observer role generally is an interface, it is only one update method, when a change in observer status, this method will be triggered calls.
  • Specifically the observed: using the role to facilitate the expansion, the specific business logic may be defined in this role.
  • Specific viewer: the viewer specific implementation of the interface, in this role, the logic is defined to be processed when the observer changes the state of the object.

Observer mode code implementation

abstract class Subject {
	private Vector<Observer> obs = new Vector<Observer>();
	
	public void addObserver(Observer obs){
		this.obs.add(obs);
	}
	public void delObserver(Observer obs){
		this.obs.remove(obs);
	}
	protected void notifyObserver(){
		for(Observer o: obs){
			o.update();
		}
	}
	public abstract void doSomething();
}
 
class ConcreteSubject extends Subject {
	public void doSomething(){
		System.out.println("被观察者事件发生");
		this.notifyObserver();
	}
}
interface Observer {
	public void update();
}
class ConcreteObserver1 implements Observer {
	public void update() {
		System.out.println("观察者1收到信息,并进行处理。");
	}
}
class ConcreteObserver2 implements Observer {
	public void update() {
		System.out.println("观察者2收到信息,并进行处理。");
	}
}
 
public class Client {
	public static void main(String[] args){
		Subject sub = new ConcreteSubject();
		sub.addObserver(new ConcreteObserver1()); //添加观察者1
		sub.addObserver(new ConcreteObserver2()); //添加观察者2
		sub.doSomething();
	}
}

operation result:

The observed events

1 viewer information received and processed.

2 observer receive information, and processes.

        The results can be seen by running, we just call the Subject approach, but at the same time observer of two related methods are called simultaneously. A closer look at the code, is actually very simple, nothing more than look in the Subject class association Observer class, and traversed it in doSomething method Observer update method on the line.

The advantages of the observer pattern

        Between the observer and the observed relationship belonging mild, and abstract is coupled, so that, for both it is relatively easy to extend it.

        Observer pattern is a common trigger mechanism, which triggers a chain form, the method sequentially processes each observer. But at the same time, it would be a drawback observer mode, because the chain is triggered when more viewers when the performance problem is more worrying. And, in the chain structure, the error of circular references are more prone to causing the system suspended animation.

to sum up

       java language, has an interface Observer, as well as its implementation class Observable, the role of observer often been achieved. We can see these two specific classes to use in the api documentation jdk.

       Did VC ++, javascript DOM or friends AWT development of all of their event-handling feel the magic, to understand the observer mode, event handling mechanism on the principle of a certain understanding. If you want to design a triggering event handling mechanism, using the Observer pattern is a good choice, AWT event handling DEM (delegate event model Delegation Event Model) is to use the observer pattern implementation.


Address reprint

Reference address

Published 75 original articles · won praise 48 · Views 350,000 +

Guess you like

Origin blog.csdn.net/KingJin_CSDN_/article/details/89452843