Notes on Big Talk Design Patterns Observer Patterns

Keywords: PHP Programming

Take a chestnut

Problem Description

Several colleagues watch the stock market during work, let the front desk MM help to see when the boss comes to check the guard, when the boss comes in, MM calls one of the colleagues, so all colleagues know, and continue to work....

Simple implementation

Front Secretary MM

/**
 * Front Secretary MM
 * Created by callmeDevil on 2019/7/27.
 */
public class Secretary {

    // List of colleagues
    private List<StockObserver> observers = new ArrayList<>();
    private String action;

    // increase
    public void attach(StockObserver observer){
        // Several colleagues asked the front desk for help, so they added several objects to the collection.
        observers.add(observer);
    }

    // notice
    public void call(){
        // When the boss comes, he notifies all registered colleagues.
        for (StockObserver observer : observers) {
            observer.update();
        }
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

}

Look at colleagues in stocks

/**
 * Look at colleagues in stocks
 * Created by callmeDevil on 2019/7/27.
 */
public class StockObserver {

    private String name;
    private Secretary sub;

    public StockObserver(String name, Secretary sub){
        this.name = name;
        this.sub = sub;
    }

    public void update(){
        System.out.println(String.format("%s %s Close the stock market and continue to work!", sub.getAction(), name));
    }

}

test

public class Test {

    public static void main(String[] args) {
        // Front Desk Girls
        Secretary mm = new Secretary();
        // A colleague looking at stocks
        StockObserver observer1 = new StockObserver("Naluto", mm);
        StockObserver observer2 = new StockObserver("What is gay", mm);

        // Front Desk Girls Write Down Two Colleagues
        mm.attach(observer1);
        mm.attach(observer2);
        // Found the Boss
        mm.setAction("The boss is back!");
        // Notify two colleagues
        mm.call();
    }

}

test result

The boss is back! Which road to close the stock market, continue to work!
The boss is back! What is gay closing the stock market, continue to work!

Existing problems

  • "Front-desk MM" and "Stock Watching Colleagues" are coupled
  • If anyone else wants to watch NBA live broadcasting, they can only change the "front MM", which does not conform to the open-closed principle.
  • Secondly, we should follow the principle of inversion of dependence so that there is no interdependence between them.

Simple implementation 2

Abstract observer

/**
 * Abstract observer
 * Created by callmeDevil on 2019/7/27.
 */
public abstract class Observer {

    protected String name;
    protected Secretary sub;

    public Observer(String name, Secretary sub) {
        this.name = name;
        this.sub = sub;
    }

    public abstract void update();

}

Front Secretary MM

/**
 * Front Secretary MM
 * Created by callmeDevil on 2019/7/27.
 */
public class Secretary {

    // List of colleagues
    private List<Observer> observers = new ArrayList<>();
    private String action;

    // increase
    public void attach(Observer observer) { //For Abstract programming, the coupling with concrete classes is reduced.
        observers.add(observer);
    }

    // reduce
    public void detach(Observer observer) { //For Abstract programming, the coupling with concrete classes is reduced.
        observers.remove(observer);
    }

    // notice
    public void call() {
        for (Observer observer : observers) {
            observer.update();
        }
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

}

A colleague looking at stocks

/**
 * A colleague looking at stocks
 * Created by callmeDevil on 2019/7/27.
 */
public class StockObserver extends Observer {

    public StockObserver(String name, Secretary sub) {
        super(name, sub);
    }

    @Override
    public void update(){
        System.out.println(String.format("%s %s Close the stock market and continue to work!", sub.getAction(), name));
    }

}

Look at NBA colleagues

/**
 * Look at NBA colleagues
 * Created by callmeDevil on 2019/7/27.
 */
public class NBAObserver extends Observer {

    public NBAObserver(String name, Secretary sub) {
        super(name, sub);
    }

    @Override
    public void update() {
        System.out.println(String.format("%s %s Close NBA Live broadcasting, keep working!", sub.getAction(), name));
    }
    
}

The test code is the same as above.

Existing problems

In fact, "Front desk MM" should also be abstracted, if the boss comes back, MM is too late to call, so inform everyone who will do the task? Yes, it was the boss himself who became the informer.

Observer model

Definition

It is also called publish-subscribe mode. This paper defines a one-to-many dependency relationship, which allows colleagues of multiple observer objects to monitor a subject object. When the state of the subject object changes, all observer objects are notified so that they can update themselves automatically.

UML diagrams

code implementation

Notifier interface

/**
 * Notifier interface
 * Created by callmeDevil on 2019/7/27.
 */
public interface Subject {

    void attach(Observer observer);
    void detach(Observer observer);
    void call();

    String getAction();
    void setAction(String action);

}

Boss

/**
 * Boss
 * Created by callmeDevil on 2019/7/27.
 */
public class Boss implements Subject {

    // List of colleagues
    private List<Observer> observers = new ArrayList<>();
    private String action;

    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void call() {
        for (Observer observer : observers) {
            observer.update();
        }
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

}

Abstract observer

/**
 * Abstract observer
 * Created by callmeDevil on 2019/7/27.
 */
public abstract class Observer {

    protected String name;
    protected Subject sub;

    public Observer(String name, Subject sub) { // Originally "front desk MM", now "abstract notifier"
        this.name = name;
        this.sub = sub;
    }

    public abstract void update();

}

A colleague looking at stocks

/**
 * A colleague looking at stocks
 * Created by callmeDevil on 2019/7/27.
 */
public class StockObserver extends Observer {

    public StockObserver(String name, Subject sub) { // Originally "front desk MM", now "abstract notifier"
        super(name, sub);
    }

    @Override
    public void update(){
        System.out.println(String.format("%s %s Close the stock market and continue to work!", sub.getAction(), name));
    }

}

"Look at NBA colleagues" is similar to "Look at stocks colleagues", which is omitted here.

test

public class Test {

    public static void main(String[] args) {
        // Boss
        Boss boss = new Boss();

        // A colleague looking at stocks
        StockObserver observer1 = new StockObserver("Naluto", boss);
        // Look at NBA colleagues
        NBAObserver observer2 = new NBAObserver("What is it? gay", boss);

        boss.attach(observer1);
        boss.attach(observer2);

        boss.detach(observer1); // Actor Halo! Spots can't beat any way! So subtract

        // Spot resurrected!
        boss.setAction("My Uchi Wave Spot has come back to life! ___________");
        // give an announcement
        boss.call();
    }

}

test result

My Uchi Wave Spot has come back to life! ___________ What's the matter? gay shuts down NBA Live and keeps working!

summary

  • What is the motivation? The disadvantage of dividing a system into a series of collaborative classes is that it needs to maintain the consistency among the related objects. We do not want to make all kinds of tight coupling in order to maintain consistency, which will bring inconvenience to maintenance, expansion and reuse.
  • When will it be used? When the change of an object needs to change other objects at the same time, and it does not know how many objects are to be changed; an abstract model has two aspects, one of which depends on the other, then the two can be encapsulated in an independent object with the observer pattern so that they can change and complex independently. Use.
  • Generally speaking, the work of the observer pattern is to decouple the coupling, so that both sides of the coupling depend on abstraction rather than on concrete, so that their changes will not affect the changes of the other side.
  • Disadvantages? Take a chestnut, such as VS2005, when you click on the running program, and after running the program, the processing pops up a console program form, the toolbar changes, the toolbox disappears... Just clicking on a "run" button makes so many changes, and each change involves different controls, and there is no way for each control to implement an "Observer" interface, that is to say, it is impossible to use the interface and realize the observation mode. Looking back at the chestnut above, although the principle of dependency reversal has been used, the "abstract notifier" still relies on the "abstract observer", that is to say, if there is no interface such as the abstract observer, the function of notification will not be completed. In addition, every specific observer, he is not necessarily "updated" method to call, as I just said, I hope that the "toolbox" is hidden, "automatic window" is open, which is not the same name method at all, this is the inadequacy of the observer mode. In. NET, event delegation can be used to better solve this shortcoming. Interested people can view other people's articles, which will not be described here.

Posted by Ilyes on Sat, 27 Jul 2019 01:50:47 -0700