What Is an Observer Pattern?
The Observer pattern facilitates communication between a parent class and any dependent child classes, allowing changes to the state of the parent class to be sent to the dependent child classes. We can use this pattern to allow the state changes in a class to be sent to all its dependent classes. The class relationship is one-to-many between the class and all its dependents.
The pattern generally consists of two base classes. The first is called the Subject class, and this class acts as the notification engine. The Observer classes act as receivers of the subject notifications. From these two base class types the concrete implementations for each type are derived: concrete subject and concrete observer.
Observers generally monitor the state of a class they are linked to and get information from that class when changes occur that they are concerned about. If we had a class that linked into many classes, and those classes wished to know about changes within it, we might use this pattern. The pattern allows code to handle the notifications automatically through the structure of the objects, instead of letting oolean logic decide. It also offers a cleaner and more intuitive way to allow communication between a single object supplying notifications and its dependent objects.
Comparison to Similar Patterns
I would say the main difference between Observer and Mediator patterns is how the objects communicate. In the Observer pattern, one object communicates with many linked objects. In the Mediator, objects in a group communicate on a one-to-one basis between each other without referencing each other. Observer subjects and singletons both pass values from a single object to many other objects. Observers use the state of the subject object and gain that state as a linked object. Observers use the state like a Memento pattern, storing parts of the state of the subject.
What We Have Learned
Observers are interesting ways to allow a one-to-many relationship for passing and sharing state between a subject and a number of observer objects. It allows an automatic relationship to be established between a subject and its observers that allows controlled information to be exchanged at key moments between these objects.
本文介绍了观察者模式的基本概念及其在软件开发中的应用。通过建立一个主题类与多个观察者类之间的联系,使得当主题的状态发生变化时,所有依赖于它的观察者都能够自动接收到通知并作出响应。观察者模式简化了对象间的通信,并提供了一种更为直观的方式来实现一对多的关系。
3000

被折叠的 条评论
为什么被折叠?



