观察者模式
The Observer Pattern is a widely used design pattern in software engineering. It's particularly useful for creating a system where an object (the subject) needs to notify a list of observers about any state changes.
观察者模式是软件工程中广泛使用的一种设计模式。它特别适用于创建一个系统,在这个系统中,一个对象(主体)需要将任何状态变化通知一系列观察者。
Motivation
假设一个场景(Scenario):股市应用(Stock Market Application)
Imagine you are developing a stock market tracking application. The application should update various displays (like mobile app views, web dashboard, and email notifications) whenever a particular stock's price changes. The main challenge here is how to efficiently and effectively notify all these different types of displays when a stock's price changes, without tightly coupling the stock data with the display components.
想象一下,您正在开发一款股票市场跟踪应用程序。每当特定股票的价格发生变化时,该应用程序都应更新各种显示(如移动应用程序视图、网络仪表板和电子邮件通知)。这里的主要挑战是如何在股票价格发生变化时高效地通知所有这些不同类型的显示屏,而不将股票数据与显示组件紧密耦合在一起。
观察者模式如何解决问题:
Defining the Subject and Observers:
- The Stock class (Subject) holds the stock data and is responsible for notifying the observers about the price changes.股票类(主题)保存股票数据,并负责将价格变化通知观察者。
- Various display elements such as MobileAppDisplay, WebDashboardDisplay, and EmailNotificationService act as Observers.各种显示元素(如 MobileAppDisplay、WebDashboardDisplay 和 EmailNotificationService)都充当观察者。
Implementation:
- The Stock class maintains a list of observers and provides methods to add or remove observers.Stock 类维护一个观察者列表,并提供添加或删除观察者的方法。
- Whenever the stock price changes, the Stock class iterates through this list and notifies each observer by calling a specific method (like
update()). 每当股票价格发生变化时,股票类都会遍历该列表,并通过调用特定方法(如update())通知每个观察者。
Sample Code
Interfaces
首先定义Observer和Subject接口
// Observer interface
public interface Observer {
void update(String stockSymbol, float stockPrice);
}
// Subject interface
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}Concrete Subject
接下来,在Stock类中实现具体的Subject接口
import java.util.ArrayList;
import java.util.List;
public class Stock implements Subject {
private List<Observer> observers;
private String stockSymbol;
private float stockPrice;
public Stock(String stockSymbol) {
this.stockSymbol = stockSymbol;
observers = new ArrayList<>();
}
public void setPrice(float price) {
this.stockPrice = price;
notifyObservers();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(stockSymbol, stockPrice);
}
}
}Concrete Observers
现在,创建一些具体的观察者
// Mobile App Display
public class MobileAppDisplay implements Observer {
@Override
public void update(String stockSymbol, float stockPrice) {
System.out.println("Mobile App Update: " + stockSymbol + " price is now " + stockPrice);
}
}
// Web Dashboard Display
public class WebDashboardDisplay implements Observer {
@Override
public void update(String stockSymbol, float stockPrice) {
System.out.println("Web Dashboard Update: " + stockSymbol + " price is now " + stockPrice);
}
}
// Email Notification Service
public class EmailNotificationService implements Observer {
@Override
public void update(String stockSymbol, float stockPrice) {
System.out.println("Email Notification: " + stockSymbol + " price is now " + stockPrice);
}
}Main Class
最后,在主程序中一起使用这些类
public class StockMarketApp {
public static void main(String[] args) {
Stock techCorpStock = new Stock("TechCorp");
Observer mobileAppDisplay = new MobileAppDisplay();
Observer webDashboardDisplay = new WebDashboardDisplay();
Observer emailService = new EmailNotificationService();
techCorpStock.registerObserver(mobileAppDisplay);
techCorpStock.registerObserver(webDashboardDisplay);
techCorpStock.registerObserver(emailService);
// Simulate a stock price change
techCorpStock.setPrice(150.0f);
}
}在本例中,当调用 techCorpStock.setPrice(150.0f) 时,会触发 notifyObservers() 方法,该方法反过来会用新价格更新每个观察者(在本例中为不同的显示系统和电子邮件通知服务)。

Create By GPT-4 in ChatGPT-Plus
评论已关闭