Observer pattern of Java design pattern

The observer pattern is also known as publish subscribe (publish / subscribe) mode defines a one to many dependency, which allows multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it will notify all observer objects so that they can update themselves automatically. There is a very bad side effect of dividing a system into a series of cooperative classes, that is, the need to Maintain consistency between related objects. We don't want to tightly couple various types in order to maintain consistency, which will bring inconvenience to maintenance, extension and reuse. What the observer pattern does is actually decoupling, so that both sides of the coupling rely on abstraction rather than concrete.

Observer mode is a widely used mode in practice. Its application scenario is, for example, a factory producing rice and N businesses selling rice. N businesses first register their contact information in this factory. When the factory produces a certain amount of rice, they will notify the N businesses to pick up the goods according to the contact information. In this example, attach and notify in the observer mode are used, that is, when the notifier's state changes, each observer is notified in turn.

Subject is an abstract notifier and observer is an abstract observer. If the derived class you want to create is a different object, you can consider using an interface to implement several of the same methods.   

The Java code is as follows:

In the above code, there are abstract observers and abstract notifiers. When the state of Subject changes, the calling function can notify the observers registered within it. This design idea is also common in daily life, such as the manufacturers and sellers of rice mentioned at the beginning. Another application scenario, for example, if a book in the bookstore is out of stock and customers still want to buy it, they can register. After the goods are available, the bookstore owner will call the customers who want to buy the book in turn. This registration mechanism is also reflected in other programming skills. For example, the program registers multiple callback functions with the underlying library. When the conditions are met, the underlying library will notify (or call) the callback function provided by the top layer.

The above code is written in Java, and it is similar in C + +. It is mainly subject that saves the pointer of observer. However, C + + should consider freeing memory. Note that when the observer itself is to be destroyed, the detach function of subject must be called, otherwise the crash may be caused by using wild pointers during update. Consider using subject to manage the lifecycle of the observer.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>