I believe everyone has seen “Pleasant Goat and Grey Wolf”, it is said that grey Wolf and sheep clan “struggle”, and every time the result is grey Wolf soar, accompanied by a “I will come back……” . Sad for grey Wolf, unable to catch sheep and abused at home by his wife pan. Why would grey Wolf do that?

Very simple, the grey Wolf itself has the attribute of “exposing track”, the sheep can know what the grey Wolf wants to do, not back.

In order to help grey Wolf get rid of the tragedy of being hit by his wife’s frying pan, he launched the “Rescue Grey Wolf” campaign, it is necessary to know the observer mode.

I. Observer model

define

The observer pattern, also known as publisk-subscribe, defines a one-to-many dependency between objects so that all dependent objects are notified and automatically update themselves when their state changes.

The characteristics of

1) The observed needs to hold one or more observer objects.

2) The change of one module in the system will be followed by some modules.

UML






As can be seen from the UML above, the observer pattern designs four roles as follows:

– Abstract observed roles: defines methods for dynamically adding, deleting, and notifying observer objects. The responsibility is to manage and notify the observer. Holds a collection of observer objects.

– Concrete Observed role: The general inheritance abstracts the observed, implements its own business logic, and initiates notification when state changes.

– Abstract observer role: Provides an interface that defines how the observer updates itself when it receives a notification.

– Concrete Observer role: Implements abstract observer interface and processes different service logic of different concrete observers.

Second, the actual combat

The Big Grey Wolf has the attribute of being observed. The sheep are always observing the big Grey Wolf, so the sheep are observers. OK, the role is determined, let’s see how it is implemented…

Abstract the observed code as follows:

Private List<Observer> observerList = new ArrayList<>(); /** * @param observer */ public void attach(observer observer) {observerList.add(observer); System.out.println("Added observer:"+ observer.getName()); } public void dettach(observer observer) {observerlist.remove (observer); System.out.println("Removed observer:"+ observer.getName()); } /** * notify all observers */ public voidnotifyObserver() {
        for (Observer observer : observerList) {
            observer.update("Grey Wolf's about to get into trouble."); }}}Copy the code

Grey Wolf is the concrete observed and inherits the abstract observed. The code is as follows:

public class Wolf extends Subject {

    public void invade(){

        System.out.println("Grey Wolf: I'm about to do something."); // notifyObserver(); }}Copy the code

The abstract observer code looks like this:

public interface Observer { String getName(); /** @param MSG */ public void update(String MSG); }Copy the code

Pleasant Goat is a concrete observer, implement abstract observer, the code is as follows:

public class PleasantSheep implements Observer{

    @Override
    public String getName() {
        return Pleasant Goat; } @override public void update(String MSG) {system.out.println ();"Pleasant Goat received a notice:"+ msg); }}Copy the code

Let’s see how the client can run the observer mode as follows:

Public class Client {public static void main(String[] args) {public static void main(String[] args) { // Observer pleasantSheep = new pleasantSheep (); Wolf. Attach (pleasantSheep); // While making coffee (); }}Copy the code

Running the client code results in the following:

Added observer: Pleasant Goat

Grey Wolf: I’m going to do something

Pleasant Goat is informed that Big Wolf is going to cause trouble

See, grey Wolf is asking for it! You deserve to get slapped with a frying pan. Grey Wolf not only informed Pleasant goat, but also lazy Goat.

The lazy goat is also a concrete observer with the following code:

public class LazySheep implements Observer {

    @Override
    public String getName() {
        return "Lazy Goat";
    }

    @Override
    public void update(String msg) {
        System.out.println("Lazy Sheep sheep received a notice:"+ msg); }}Copy the code

The client code is as follows:

Public class Client {public static void main(String[] args) {public static void main(String[] args) { // Observer pleasantSheep = new pleasantSheep (); Wolf. Attach (pleasantSheep); // Observer lazySheep = new lazySheep (); Wolf. Attach (lazySheep); // While making coffee (); }}Copy the code

Create a lazy sheep observer and add it to the observer collection. The lazy sheep will be notified as well.

Added observer: Pleasant Goat

Added observer: Lazy Goat goat

Grey Wolf: I’m going to do something

Pleasant Goat is informed that Big Wolf is going to cause trouble

Lazy Sheep sheep received a notice: Grey Wolf is going to make trouble

To help grey Wolf escape this fate, remove the observer from the collection and it is OK. The code is as follows:

Public class Client {public static void main(String[] args) {public static void main(String[] args) { // Observer pleasantSheep = new pleasantSheep (); Wolf. Attach (pleasantSheep); // Observer lazySheep = new lazySheep (); Wolf. Attach (lazySheep); // While making coffee (); // Delete observer wolf.dettach(pleasantSheep); wolf.invade(); }}Copy the code

Run the client again and the result is as follows:

Added observer: Pleasant Goat

Added observer: Lazy Goat goat

Grey Wolf: I’m going to do something

Pleasant Goat is informed that Big Wolf is going to cause trouble

Lazy Sheep sheep received a notice: Grey Wolf is going to make trouble

Deleted observer: Pleasant Goat

Grey Wolf: I’m going to do something

Lazy Sheep sheep received a notice: Grey Wolf is going to make trouble

As you can see, by removing Pleasant from the observer set, she will no longer receive notifications.

Advantages and disadvantages of the observer model

advantages

1) Abstract coupling between observer and observed. The observer pattern is easily extensible; the observed only holds a collection of observers and does not need to know the implementation within a specific observer.

2) Maintain a high degree of collaboration between objects. When the observed changes, all the observed will be notified, and then make corresponding actions.

disadvantages

1) If there are too many observers, it will take a lot of time for the observers to notify the observers, affecting the performance of the system.

2) When one observer in the observer set is wrong, the system will be jammed, so asynchronous mode is generally adopted.

Four, comparison,

Contrast with the proxy mode: The main difference between the observer mode and the proxy mode is that they have different functions. The observer mode emphasizes the observed feedback results, while the proxy mode is the same root responsible for doing the same things.

conclusion

Java has provided an Observable class and an Observer interface, that is to say, Java has implemented the definition of Observer mode. It can be seen that the Observer mode is widely used in the program system. Not only Java, but Android also frequently sees the application of Observer mode. Such as OnClickListener, Rxjava, etc. I will fill in the prototype patterns that are part of the creation pattern in the next post, which will be broken down next time. See you.

Design pattern Java source GitHub download: github.com/jetLee92/De…