what? The goddess sent a circle of friends, come and watch the Java design pattern: observer pattern

Observer mode

Example

WeChat public account, you can receive the push message if you follow it, and you will not receive it if you unfollow it

definition

Defines a one-to-many dependency relationship between objects. When one end of the object changes, all its dependents will be notified and automatically updated (the update method is called). The
observer mode is also called: monitoring mode, publish and subscribe mode. Provides a design method of loose coupling between objects.
Interface-oriented programming, registration and callback mechanism

Design Principles

Work hard for loosely coupled design between interactive objects

intention

Defines a one-to-many dependency relationship between objects. When one end of the object changes, all its dependents will be notified and automatically updated

Mainly solve the problem

The problem of notifying other objects when the state of an object changes, and taking into account ease of use and low coupling to ensure a high degree of collaboration

When to use

When the state of an object changes, all dependents will be notified

Pros and cons

advantage:

  1. There is an abstract coupling between the observer and the observed
  2. A trigger mechanism can be established

Disadvantages:

  1. If there are many observers, notifying all observers is time-consuming
  2. If there is a circular dependency between the observer and the observation target, the observation target will trigger a cyclic call between them, which may cause the system to crash
  3. Observers cannot know how the observed target object has changed, only that the observed target has changed

Let's look at the class diagram below:
Insert picture description here
the roles involved:

  1. Abstract subject (Subject) role: The subject role stores all references to observers in a collection (such as a list collection). Each subject can have any number of observers. The abstract subject provides an interface that can be added or deleted Observer, the subject role is also called the abstract Observable role, which is generally implemented by an abstract class or interface
  2. Abstract observer (Observer) role: define an interface for all specific observers, update themselves when notified by the subject, this interface is called update interface, abstract observer role is generally implemented by an abstract class or interface
  3. Concrete subject (ConcreteSubject) role: save the relevant state into a specific observer object, and notify all registered observers when the internal state of the specific subject changes. The specific subject role is also called the concrete observer (Concrete Observable) role , Usually implemented by a subclass
  4. Concrete observer (ConcreteObserver) role: stores the state that is self-consistent with the state of the subject, and implements the update interface required by the abstract observer role in order to coordinate its state with the state of the subject, usually implemented by a subclass

Subject class:

public interface Subject {
    
    

    /** 添加一个新的观察者 */
    void attach(Observer observer);

    /** 移除一个已经登记过的观察者 */
    void detach(Observer observer);

    /** 通知所有已经登记过的观察者 */
    void notifyObservers();
}

ConcreteSubject class:

public class ConcreteSubject implements Subject {
    
    

    private List<Observer> list = new ArrayList<>();

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

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

    @Override
    public void notifyObservers() {
    
    
        for (Observer o : list) {
    
    
            o.update();
        }
    }
}

Observer class:

public interface Observer {
    
    

    /** 观察者更新自己 */
    void update();
}

ConcreteObserver class:

public class ConcreteObserver implements Observer {
    
    
    @Override
    public void update() {
    
    
        System.out.println("I am notified");
    }
}

The story of the goddess and the suitor

The goddess Cuihua is a flower in the village, and many people pursue it, such as Lao Wang who lives next door, Xiao Ming who grew up with him, and Mr. Tony from the barber shop in the village. They are all Cuihua’s WeChat friends. Always pay attention to the dynamics of Cuihua. Let's write a small example
based on the above scenario: Observable class:

public interface Observable {
    
    

    /** 添加观察者 */
    void addObserver(Observer observer);

    /** 移除观察者 */
    void removeObserver(Observer observer);

    /** 通知所有观察者 */
    void notifyAllObservers();

}

The circle of friends of the goddess Cuihua:

public class GoddessPyq implements Observable {
    
    

    private List<Observer> list = new ArrayList<>();

    private String msg;

    @Override
    public void addObserver(Observer observer) {
    
    
        list.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
    
    
        list.remove(observer);
    }

    public void pushMsg(String msg) {
    
    
        this.msg = msg;
        System.out.println("发个朋友圈:" + msg);
        notifyAllObservers();
    }

    @Override
    public void notifyAllObservers() {
    
    
        for (Observer o : list) {
    
    
            o.update(msg);
        }

    }
}

Observer class:

public interface Observer {
    
    

    /** 更新 */
    void update(Object object);
}

Lao Wang, Xiao Ming, Tony's circle of friends: always pay attention to whether Cuihua has posted to circle of friends

public class LaoWang implements Observer {
    
    
    @Override
    public void update(Object object) {
    
    
        System.out.println("LaoWang-隔壁女神:" + object);
    }
}
public class XiaoMing implements Observer {
    
    
    @Override
    public void update(Object object) {
    
    
        System.out.println("XiaoMing-我亲爱的女神:" + object);
    }
}
public class Tony implements Observer {
    
    
    @Override
    public void update(Object object) {
    
    
        System.out.println("Tony-经常来的美女:" + object);
    }
}

Test category: The goddess posted a circle of friends, Pharaoh, Xiaoming, Tony can all receive notifications

public class Test {
    
    
    public static void main(String[] args) {
    
    
        GoddessPyq pyq = new GoddessPyq();
        pyq.addObserver(new LaoWang());
        pyq.addObserver(new Tony());
        pyq.addObserver(new XiaoMing());

        pyq.pushMsg("今天上班迟到了,好想有人送我上班");
        System.out.println();
        pyq.pushMsg("看上了一个包包,可惜没钱了");
        System.out.println();
        pyq.pushMsg("今天电脑坏了");
    }
}

Insert picture description here
Class Diagram:
Insert picture description here

Implementation in Java

Java provides a general implementation of the observer pattern:
Java.util. Observable: Observable (theme), specific topics extend it
java.util.Observer: Observer interface, specific observers implement this interface

public class JDKObserverSample {
    
    

	public static void main(String[] args) {
    
    
		Observable subject1 = new Observable() {
    
    
			public synchronized void notifyObservers(Object data) {
    
    
				setChanged();
				super.notifyObservers(data);
			}
		};

		subject1.addObserver(new Observer() {
    
    
			@Override
			public void update(Observable o, Object arg) {
    
    
				System.out.println("观察者1收到通知被更新了..." + arg);
			}
		});

		subject1.addObserver(new Observer() {
    
    
			@Override
			public void update(Observable o, Object arg) {
    
    
				System.out.println("观察者2收到通知被更新了..." + arg);
			}
		});

		subject1.notifyObservers("change1");
		subject1.notifyObservers("change2");
	}
}

It should be noted that:
Observable is a class and does not implement an interface. The theme must inherit from it. If the theme wants to inherit another class, this will be a problem. Limit its reuse potential

Guess you like

Origin blog.csdn.net/qq_34365173/article/details/108063496