The behavior pattern is used to describe the complex flow control of the program at runtime, that is, to describe how multiple classes or objects cooperate to accomplish tasks that a single object cannot accomplish alone. It involves the assignment of responsibilities between algorithms and objects.
Behavior pattern is divided into class behavior pattern and object behavior pattern. The former adopts inheritance mechanism to allocate behavior among classes, and the latter adopts combination or aggregation to allocate behavior among objects. The object behavior pattern has more flexibility than the class behavior pattern because the combinatorial or aggregative relationship is less coupled than the inheritance relationship and meets the “composite reuse principle”.
Behavioral patterns can be divided into:
- Template method pattern
- The strategy pattern
- Command mode
- Chain of Responsibility model
- The state pattern
- Observer model
- The mediator pattern
- Iterator pattern
- Visitor pattern
- Memo mode
- Interpreter mode
The above 11 behavior patterns, except template method pattern and interpreter pattern are class behavior pattern, the other all belong to object behavior pattern.
6.1 Observer Mode
6.1.1 overview
The observer pattern, also known as the Publish/Subscribe pattern, defines a one-to-many dependency that allows multiple observer objects to listen on a subject object at the same time. The topic object notifies all observer objects of state changes so that they can update themselves automatically.
6.1.2 structure
There are the following roles in Observer mode:
Subject
Abstract themes the abstract theme role stores all observer objects in a collection. Each theme can have any number of observers. Abstract themes provide an interface to add and remove observer objects.ConcreteSubject
: specific topic (specific observed). This role stores the relevant state in the specific observer object and notifies all registered observers when the internal state of the specific topic changes.Observer
Abstract Observer, an abstract class for an observer, defines an update interface that updates itself when notified of topic changes.ConcrereObserver
: A concrete observer that implements an update interface defined by an abstract observer to update its own state when notified of a topic change.
6.1.3 Case Implementation
Wechat official account
In the use of wechat public number, we will have such an experience, when you pay attention to the public number in the new content update, it will be pushed to the wechat user concerned about the public number. We use the observer mode to simulate such a scene. The wechat user is the observer, and the wechat public account is the observed. Multiple wechat users follow the official account of the Program ape.
The class diagram is as follows:
The code is as follows:
Define an abstract observer class that defines an updated method
public interface Observer {
void update(String message);
}
Copy the code
Define the specific observer class, wechat user is the observer, which implements the update method
public class WeixinUser implements Observer { // Wechat account name
private String name;
public WeixinUser(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + "-"+ message); }}Copy the code
Define abstract topic class, provide attach, detach, notify three methods:
public interface Subject { // Add subscribers
public void attach(Observer observer); // Delete the subscriber
public void detach(Observer observer);
// Notify subscribers of updates
public void notify(String message);
}
Copy the code
Wechat public account is a specific theme (specific observed), which stores the wechat users who subscribe to the public account, and implements the method in the abstract theme
public class SubscriptionSubject implements Subject {
// Store wechat users who subscribe to public accounts
private List<Observer> weixinUserlist = new ArrayList<Observer>();
@Override
public void attach(Observer observer) {
weixinUserlist.add(observer);
}
@Override
public void detach(Observer observer) {
weixinUserlist.remove(observer);
}
@Override
public void notify(String message) {
for(Observer observer : weixinUserlist) { observer.update(message); }}}Copy the code
Client program
SubscriptionSubject mSubscriptionSubject=new SubscriptionSubject();
// Create a wechat user
WeixinUser user1=new WeixinUser("Sun Wukong");
WeixinUser user2=new WeixinUser("Pig Wuneng");
WeixinUser user3=new WeixinUser("Sha Wu Jing");
// Subscribe to the public account
mSubscriptionSubject.attach(user1);
mSubscriptionSubject.attach(user2);
mSubscriptionSubject.attach(user3);
// Public account updates send messages to subscribed wechat users
mSubscriptionSubject.notify("The dark Horse column has been updated.");
Copy the code
6.1.4 the pros and cons
Advantages:
- The coupling relationship between the target and the observer is abstract.
- The observed sends a notification, all registered observers will receive the message [can implement broadcast mechanism]
Disadvantages:
- If there are too many observers, it will take time for all observers to receive the notification sent by the observer
- If the observed has a loop dependency, then the observed sends a notification which causes the observer to loop, causing the system to crash
6.1.5 Application Scenarios
- Objects have a one-to-many relationship. Changes in the state of one object affect other objects.
- When an abstract model has two aspects, one of which depends on the other.
The implementation provided in the 6.1.6 JDK
In Java, the Observer pattern is defined through the java.util.Observable class and the java.util.Observer interface, and instances of the Observer pattern can be written by implementing their subclasses.
Class 1, observables
An Observable is an abstract object class. It has a Vector member variable that holds all Observable objects to be notified. Here are three of its most important methods.
void addObserver(Observer o)
Method: Used to add a new observer object to the collection.void notifyObservers(Object arg)
Method: calls all observer objects in the collectionupdate
Method to notify them that the data has changed. Observers who join the collection later are usually notified first.void setChange()
Method: Used to set aboolean
An internal flag for a type indicating that the target object has changed. When it istrue
When,notifyObservers()
Before the observer is notified.
2, Observer interface
The Observer interface is an abstract Observer that monitors changes in the target object, notifies the Observer when the target object changes, and calls the Update method to do the work accordingly.
The police caught the thief
Police catching thieves can also be implemented using the observer model, where the police are the observers and the thief is the observed. The code is as follows:
The thief is an Observable, so it needs to inherit the Observable class
public class Thief extends Observable {
private String name;
public Thief(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName(a) {
return name;
}
public void steal(a) {
System.out.println("Thief: I stole something, have someone to catch me!!");
super.setChanged(); //changed = true
super.notifyObservers(); }}Copy the code
The police is an Observer, so it needs to implement the Observer interface
public class Policemen implements Observer {
private String name;
public Policemen(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName(a) {
return name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("The police." + ((Thief) o).getName() + ", I have been watching you for a long time, you can keep silent, but anything you say can and will be used against you in a court of law!!"); }}Copy the code
Client code
// Create thief object
Thief t = new Thief("Next door Lao Wang");
// Create a police object
Policemen p = new Policemen("Xiao li");
// Keep the police on the thief
t.addObserver(p);
// Thieves steal things
t.steal();
Copy the code