To solve the problem

A key role of the observer pattern, also known as the publish-subscribe pattern, is to decouple roles.

Application scenarios

The common application scenario is distributed transaction processing with MVC architecture, but we can also apply it to decoupling.

Schematic Diagram (UML)

  • Observer: The Observer interface, which is the action that should be performed when the Observer observes a change

  • ConcreteObserver: Entity object that concretes an operation

  • Subject: a Subject, also known as the observed, consists of three actions: adding, deleting, and notifying observed objects. It holds one property: the list of observed objects

The sample

There are many examples of publish-subscribe, but let’s take an example of simple decoupling: when a request comes in, I need to invoke multiple dependent services (two in this case) and return the result

Observer: Here I interpret it as a background service that needs to be called to retrieve data as soon as a request is received

public interface Server<T> { 
    public T excute(Request params); 
}

public class RpcServer<T> implements Server<T> { 
    public T excute(Request params) { 
        returnnull; // Define specific service calls... } // Parameter parsing, result conversion, exception handling, disaster recovery, etc. } public class HttpServer<T> implements Server<T> { public T excute(Request params) {returnnull; // Define specific service calls... } // Parameter parsing, result conversion, exception handling, disaster recovery, etc. }Copy the code

Suject: Understood here as an HTTP service that calls multiple background services to provide data to the foreground

*/ public interface service <R> {public R getData(); } public class HttpService implements Service<List< Object>> { public List<Server> servers = Lists.newArrayList(); public List<Object>getData() { List<Object> result = Lists.newArrayList(); // This can be done asynchronously...for (Server server : servers) { 
            result.add(server.excute(null)); 
        } 
        returnnull; }}Copy the code

reference

https://en.wikipedia.org/wiki/Observer_pattern