观察者,装饰,策略模式
2025-02-15 14:27 钟铧若岩 阅读(5) 评论(0) 编辑 收藏 举报观察者模式(Observer Pattern)
using System; using System.Collections.Generic; // 观察者接口 public interface IObserver { void Update(string message); } // 主题接口 public interface ISubject { void Attach(IObserver observer); void Detach(IObserver observer); void Notify(string message); } // 具体主题类 public class ConcreteSubject : ISubject { private List<IObserver> observers = new List<IObserver>(); public void Attach(IObserver observer) { observers.Add(observer); } public void Detach(IObserver observer) { observers.Remove(observer); } public void Notify(string message) { foreach (var observer in observers) { observer.Update(message); } } } // 具体观察者类 public class ConcreteObserver : IObserver { private string name; public ConcreteObserver(string name) { this.name = name; } public void Update(string message) { Console.WriteLine($"{name} received message: {message}"); } }
装饰器模式(Decorator Pattern)
// 组件接口 public interface IComponent { void Operation(); } // 具体组件类 public class ConcreteComponent : IComponent { public void Operation() { Console.WriteLine("ConcreteComponent operation"); } } // 装饰器抽象类 public abstract class Decorator : IComponent { protected IComponent component; public Decorator(IComponent component) { this.component = component; } public virtual void Operation() { component.Operation(); } } // 具体装饰器类 public class ConcreteDecorator : Decorator { public ConcreteDecorator(IComponent component) : base(component) { } public override void Operation() { base.Operation(); Console.WriteLine("ConcreteDecorator additional operation"); } }
策略模式(Strategy Pattern)
// 策略接口 public interface IStrategy { int Execute(int a, int b); } // 具体策略类 public class AddStrategy : IStrategy { public int Execute(int a, int b) { return a + b; } } public class SubtractStrategy : IStrategy { public int Execute(int a, int b) { return a - b; } } // 上下文类 public class Context { private IStrategy strategy; public Context(IStrategy strategy) { this.strategy = strategy; } public int ExecuteStrategy(int a, int b) { return strategy.Execute(a, b); } }
策略模式如何提高代码的可维护性和可扩展性
可维护性:将不同的算法封装在独立的策略类中,每个策略类只负责自己的算法逻辑,代码结构清晰,便于修改和维护。
可扩展性:如果需要添加新的算法,只需创建一个新的策略类并实现策略接口,然后在上下文中使用新的策略类即可,无需修改现有的代码,符合开闭原则。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?