define
- The observer pattern is a behavioral design pattern.
- There is a one-to-many relationship between the object subscriber and the observer. When the subscriber object sends changes, the observer can perceive the changes and make corresponding events.
Custom code implementation
- In this case, the subscriber is the store, and the observer is two users who like Apple and Huawei. Through different products purchased in the store, the user generates different response events.
- Create a subscriber object.
/** * @author ZRH */ public class AppleShop {/** * @author ZRH */ private String apple = "..." ; /** * watch */ private List<UserBuy> List; Public AppleShop() {list = lists.newarrayList (); /** * Initialize the observation group object container */ public AppleShop() {list = Lists. ** @param apple */ public void setApple(String apple) {this.apple = apple; info(); } /** * get the subscriber object content ** @return */ public String getApple() {return this. } /** * Observers register with the container ** @param userBuy */ public void setUserBuy(userBuy userBuy) {this.list.add(userBuy); } /** * inform observer */ public void info() {list.foreach (o -> o.Uyapple ()); }}Copy the code
- Define the observer interface and the observer implementation
/** * observer interface, all observers must implement the current interface, aggregate objects. */ public interface UserBuy {/** * declare the observer event */ void buyApple(); }Copy the code
/** * @author ZRH */ public class implements UserBuy {/** * implements UserBuy */ private AppleShop AppleShop; public UsUser(AppleShop appleShop) { this.appleShop = appleShop; } @override public void buyApple() {if (" apple ".equals(appleShop. GetApple ())) {system.err. Println (" appleShop. I like..." ); } else {system.err. Println (" I'm UsUser store don't have apple, I don't buy... ") ); }}}Copy the code
/** * @author ZRH */ public class implements UserBuy {/** * implements user object */ private AppleShop appleShop; public ChinaUser(AppleShop appleShop) { super(); this.appleShop = appleShop; } @override public void buyApple() {if (" huawei ".equals(appleShop. GetApple ())) {system.err. Println (" ChinaUser "); I like..." ); } else {system.err. Println (" I am a ChinaUser shop has no Huawei, I do not buy..." ); }}}Copy the code
- The test results
Public static void main(String[] args) {shopObserved(); } private static void shopObserved() {// create subscriber AppleShop AppleShop = new AppleShop(); UserBuy usUser = new usUser (appleShop); UserBuy chainUser = new ChinaUser(appleShop); // Register the observer as a subscriber. Appleshop.setuserbuy (usUser); appleShop.setUserBuy(chainUser); While (true) {Scanner Scanner = new Scanner(system.in); appleShop.setApple(scanner.nextLine()); }}}Copy the code
Use spring’s built-in observer pattern
- In spring’s core board, rt.jar, there are classes and interfaces that help us with the event Observer pattern.
- We just need to inherit the subscriber class and implement the observer interface to complete the design pattern.
/** * @author ZRH */ Public Subscription extends Observable {/** * Constructs an observer */ Public Subscription() { super(); } /** * Observer register subscriber ** @param o */ @override public void addObserver(Observer o) {super.addobServer (o); } /** * deleteObserver ** @param o */ public void deleteObserver(ObservedU o) {super.deleteobserver (o); } /** * Trigger an event */ @override public void notifyObservers() {// This method is used to mark that the object is astute, and must be called otherwise, observers will not be notified. super.setChanged(); // notifyObservers to trigger super.notifyobservers (); }}Copy the code
Public class ObservedU implements Observer {/** * implements Observer ** @author ZRH */ public class ObservedU implements Observer {/** * implements Observer ** @param subscription */ public ObservedU(Subscription subscription) { subscription.addObserver(this); } @override public void update(Observable o, Observable O, Observable O, Observable O) Object arg) {if (" apple ".equals(arg)) {system.err. Println (" I'm an observer U store has apples, I like... ") ); } else {system.err. Println (" I'm the observer U store don't have apples, I don't buy... ") ); }}}Copy the code
Public class ObservedC implements Observer {/** * implements Observer ** @author ZRH */ public class ObservedC implements Observer {/** * implements Observer ** @param subscription */ public ObservedC(Subscription subscription) { subscription.addObserver(this); } @override public void update(Observable o, Observable O, Observable O, Observable O) Object arg) {if (" huawei ".equals(arg)) {system.err. Println (" I am the observer C store has Huawei, I like... ") ); } else {system.err. Println (" I am an observer C shop does not have Huawei, I do not buy... ") ); }}}Copy the code
- The test results
Public static void main(String[] args) {/** * @author ZRH */ public class TestObserved {public static void main(String[] args) observed(); } private static void observed() {Subscription = new Subscription(); // New ObservedU(subscription); new ObservedC(subscription); While (true) {Scanner Scanner = new Scanner(system.in); / / notify observers trigger subscription. NotifyObservers (scanner. NextLine ()); }}Copy the code
Actual Usage Scenario
- In Java. Util. EventListener and javax.mail servlet. HTTP. HttpSessionBindingListener and Javax.mail. Servlet. HTTP. HttpSessionAttributeListener and so on are the application of the observer design pattern.
- Reducing coupling between objects, changing subscribers or observers has no other effect.
- The above code demo is mainly used to show the basic principles of the observer design pattern. It needs to be improved and changed according to the actual scenarios and business requirements.
- Finally, learn with an open mind and make progress together