
初探设计模式:观察者与策略模式解析
下载需积分: 38 | 11KB |
更新于2025-04-16
| 195 浏览量 | 4 评论 | 举报
收藏
设计模式是软件工程中一种非常重要的编程范式,它提供了在特定情况下如何解决问题的最佳实践。观察者模式(Observer Pattern)和策略模式(Strategy Pattern)是其中较为常见的两种行为型模式。通过这两个模式的具体例子,我们可以更好地理解它们的定义、使用场景、优缺点以及在实际开发中的应用。
首先我们来探讨观察者模式。观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听一个主题对象,当主题对象的状态发生变化时,所有依赖于它的观察者都会收到通知并自动更新。这种模式特别适用于事件处理系统、消息系统和发布-订阅系统。
观察者模式通常包含如下角色:
1. 主题(Subject):提供注册和移除观察者的接口,维护观察者列表,并在状态改变时通知所有观察者。
2. 观察者(Observer):定义了更新接口,使得在主题状态改变时能够收到通知。
3. 具体主题(ConcreteSubject):实现主题接口,存储有关状态,状态改变时通知所有已注册的观察者。
4. 具体观察者(ConcreteObserver):实现观察者接口以保持对主题状态的引用。
假设我们正在开发一个天气预报系统,我们想要当天气变化时,自动更新在界面上显示的温度和湿度信息,同时也要更新存储在数据库中的天气数据。这时,我们可以使用观察者模式:
```java
// 主题接口
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
// 观察者接口
public interface Observer {
void update(float temp, float humidity);
}
// 具体主题
public class WeatherData implements Subject {
private List<Observer> observers;
private float temperature;
private float humidity;
public WeatherData() {
observers = new ArrayList<>();
}
public void setMeasurements(float temperature, float humidity) {
this.temperature = temperature;
this.humidity = humidity;
notifyObservers();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
@Override
public void notifyObservers() {
for (Observer o : observers) {
o.update(temperature, humidity);
}
}
}
// 具体观察者
public class CurrentConditionsDisplay implements Observer {
private float temperature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
@Override
public void update(float temp, float humidity) {
this.temperature = temp;
this.humidity = humidity;
display();
}
public void display() {
System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity");
}
}
```
接下来,我们来探讨策略模式。策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以相互替换,并且算法的变化不会影响到使用算法的客户。策略模式是一种行为型设计模式,通常适用于一个类定义了多种行为,并且这些行为在这个类内是可以互换的。
策略模式通常包含如下角色:
1. 上下文(Context):持有一个策略接口的引用,最终使用策略对象来执行策略的方法。
2. 策略(Strategy):定义了算法的行为,它通常由上下文调用,并由具体策略实现。
3. 具体策略(ConcreteStrategy):实现策略接口,提供具体的算法实现。
举个例子,假设我们正在开发一个支付系统,这个系统需要支持多种支付方式(如信用卡支付、支付宝支付等)。为了实现不同支付方式的灵活切换,我们可以使用策略模式。
```java
// 策略接口
public interface PaymentStrategy {
void pay(int amount);
}
// 具体策略
public class CreditCardStrategy implements PaymentStrategy {
private String name;
private String cardNumber;
private String cvv;
private String dateOfExpiry;
public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate) {
this.name = nm;
this.cardNumber = ccNum;
this.cvv = cvv;
this.dateOfExpiry = expiryDate;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid with credit/debit card");
}
}
public class PayPalStrategy implements PaymentStrategy {
private String emailId;
private String password;
public PayPalStrategy(String email, String pwd) {
this.emailId = email;
this.password = pwd;
}
@Override
public void pay(int amount) {
System.out.println(amount + " paid using Paypal.");
}
}
// 上下文
public class ShoppingCart {
// List of items in cart.
private List<Item> items;
public ShoppingCart() {
this.items = new ArrayList<>();
}
public void addItem(Item item) {
this.items.add(item);
}
public void removeItem(Item item) {
this.items.remove(item);
}
public int calculateTotal() {
int sum = 0;
for (Item item : items) {
sum += item.getPrice();
}
return sum;
}
public void checkout(PaymentStrategy paymentMethod) {
int amount = calculateTotal();
paymentMethod.pay(amount);
}
}
// 使用策略模式的示例
public class StrategyPatternDemo {
public static void main(String[] args) {
Item item1 = new Item("1234", 10);
Item item2 = new Item("5678", 40);
ShoppingCart cart = new ShoppingCart();
cart.addItem(item1);
cart.addItem(item2);
// 支付方式: 信用卡
cart.checkout(new CreditCardStrategy("Pankaj", "1234567890123456", "786", "12/15"));
// 支付方式: PayPal
cart.checkout(new PayPalStrategy("[email protected]", "mypassword"));
}
}
```
以上代码展示了如何通过支付策略接口,灵活地切换不同的支付方式。这是策略模式的一个典型应用场景。
总结来看,观察者模式和策略模式都属于行为型设计模式,它们在软件设计中广泛用于解决特定问题,提供了一种设计思路来实现系统组件间的松耦合和更好的灵活性。观察者模式常用于实现响应式编程、事件驱动系统,而策略模式则适用于算法的选择和多态算法实现。正确地理解和应用这些模式,将有助于我们编写出更易于维护和扩展的代码。
相关推荐



















资源评论

Unique先森
2025.08.15
对于设计模式的初学者来说,这份资料是一份难得的入门资料,强烈推荐。

今年也要加油呀
2025.06.28
适合初学者理解的设计模式入门指南,内容贴近实际,易于消化理解。

战神哥
2025.04.09
通过实例解析观察者和策略模式,让设计模式的学习变得更加直观。

ali-12
2025.02.19
帮助初学者清除设计模式学习的迷雾,实践与理论相结合,非常实用。

zhaoyale
- 粉丝: 3
最新资源
- 整合支付宝、财付通与网银的支付接口技术文档
- 密码查看工具GetPassword.exe,尝试获取插件密码
- 114BT开源源码免费分享与修改说明
- JCreator Pro:轻量级Java开发工具推荐
- TA-Lib技术分析库:支持多种编程语言与金融指标计算
- 谷歌分析源码ga.js全面解析与代码优化
- 淘宝账号检测工具包与相关软件资源
- 迷你二胡:VSTi乐器插件的音乐创作利器
- Etherpeek NX及其相关工具介绍
- AlphaControl 8.13 第三方组件支持与配置指南
- 杜比高级音频技术解析与正版软件介绍
- HTML全景三维商品展示技术实现详解
- 4899空口令探测工具包及其使用指南
- Passthru技术在网络过滤中的应用与解析
- 基于SSH与Oracle的办公自动化系统实现
- 汉字转拼音工具支持多系统与多音字处理
- Unity3D第三人称射击游戏源码,适合新手学习
- LinuxLive USB Creator 2.8.19:轻松制作可携带Linux系统的U盘
- 适用于Win7的高效PDF打印机工具及注册码分享
- VB6.0中文正式版:事件驱动编程语言与快速应用开发
- 飞飞仿奇热模板完整版:高效建站与流量变现解决方案
- 东南大学模式识别课程设计:人脸识别实战
- Packet Tracer网络模拟软件与使用教程
- 红色风格资讯网站模板,适用于政府及事业单位建站