Observer Pattern

本文介绍了观察者模式的基本概念及其在软件开发中的应用。通过建立一个主题类与多个观察者类之间的联系,使得当主题的状态发生变化时,所有依赖于它的观察者都能够自动接收到通知并作出响应。观察者模式简化了对象间的通信,并提供了一种更为直观的方式来实现一对多的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

href="file:///C:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/msohtml1/01/clip_filelist.xml" rel="File-List" />

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.

  UML for Observer Pattern

 

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值