Observer design pattern

zhaozj2021-02-16  55

Java is in depth to a certain extent, which is inevitable to meet Design Pattern, understanding design patterns, which will have a deeper understanding of the interface or abstract category application in Java. Design mode is widely used in the Java's medium-sized system, follows certain programming modes to make their code easy to understand, easy to communicate, OBServer mode is a common mode, especially in interface design, and This site is concerned with the application of Java in an e-commerce system, so I want to analyze OBServer applications from e-commerce instances.

Although the online store has a variety of features, each site has its own characteristics, but there is also its general commonality, and the "community" is in order to inform the subscriber in time, it is a common mode in many online stores, this mode Similar to OBServer Patern.

Specifically, if there is a change in the online store in the name price, if the system can automatically notify the member, it will be a major feature from the online store to distinguish the traditional store. This needs to be added to the Observer in the product product so that the OBServer can automatically observe this change when the product details change, and the timely UPDATE or NOTIFY action can be performed.

Java's API also provides us with ready-made Observer interface java.util.observer. We can use it directly.

We must use extends java.util.observer to truly use it: 1. Provide the method of add / delete observer; 2. Provide all Observer methods for Notisfy;

// Product Category Available for JSP Use UseBean Call This category Mainly Perform the Product Database Plug Insert Update Public Class Product Extends Observable {Private String Name; PUBLIC STRING GetName () {Return Name;} PUBLIC VOID SETNAME ()} THIS.NAME = Name; // Set the change point setChanged (); NotifyObservers (name);} public float getprice () {Return Price;} public void setprice () {this.price = price; // Set change point setChanged ); NOTIWOBSERVERS (New float (price));} // The following can be a database update insert command. Public void savetoDB () {..................... }

We noticed that in the setxxx method in the Product category, we set the Notify method, when the JSP form call setXXX (how to call my other article), actually triggered the NotisfyobServers method, which will notify The corresponding observers should take action.

Let's take a look at these observer's code. What actions they have taken:

// Observer NameObserver mainly uses public class nameobser loading name {private string name = null; public void update (Observable Obj, Object Arg) {ix

转载请注明原文地址:https://www.9cbs.com/read-20602.html

New Post(0)