课程简介
课程简介
本课程通过对比23种设计模式的适用场景、优缺点及实现复杂度,总结选型原则(如根据变化点选择模式、避免过度设计),帮助学员在项目中快速选择最合适的模式,减少试错成本。课程包含扩展性、复杂度、性能等对比维度,以及策略模式、装饰器模式等常见模式的对比分析,结合实战案例讲解如何避免单例模式内存泄漏等典型问题。
前置依赖课程
后续扩展课程
课程大纲
- 1.1 扩展性对比45min
- 1.2 复杂度与可读性45min
- 1.3 性能影响分析45min
- 2.1 策略模式 vs if-else60min
- 2.2 装饰器模式 vs 继承60min
- 2.3 观察者模式 vs 事件总线60min
- 3.1 根据变化点选择模式60min
- 3.2 避免过度设计与滥用60min
- 3.3 模式组合使用技巧60min
课程资料
设计模式对比与选型指南:如何选择合适模式
第一章 模式对比维度
1.1 扩展性对比
扩展性是衡量设计模式能否适应需求变化的核心指标。以**策略模式(Strategy Pattern)和模板方法模式(Template Method Pattern)**为例:
策略模式:通过组合方式将算法封装为独立对象,新增策略时无需修改现有代码(符合开闭原则)。例如电商支付场景中,可动态切换支付宝、微信支付等策略。
模板方法模式:通过继承方式定义算法骨架,子类重写步骤实现扩展。若需新增算法步骤,必须修改父类(违反开闭原则)。
本节小结
- 策略模式扩展性强,适合算法频繁变化的场景
- 模板方法模式扩展性弱,适合算法骨架稳定的场景
1.2 复杂度与可读性
复杂度直接影响代码维护成本。对比装饰器模式(Decorator Pattern)和继承:
| 特性 | 装饰器模式 | 继承 |
|---|---|---|
| 类数量 | 动态增加,按需组合 | 固定,需预先设计层次 |
| 职责单一性 | 每个装饰器仅关注一个功能扩展 | 子类可能承担多重职责 |
| 可读性 | 需理解组合逻辑,适合复杂场景 | 直观,适合简单场景 |
// 装饰器模式示例:为文本添加边框和阴影
public interface IText { string Render(); }
public class PlainText : IText { public string Render() => "Hello"; }
public class BorderDecorator : IText {
private IText _text;
public BorderDecorator(IText text) => _text = text;
public string Render() => $"┌─┐\n│{_text.Render()}│\n└─┘";
}
本节小结
- 装饰器模式通过组合降低复杂度,但需权衡可读性
- 继承简单直接,但易导致类爆炸和职责混乱
1.3 性能影响分析
性能是选型时不可忽视的因素。以**单例模式(Singleton Pattern)**为例:
- 饿汉式单例:类加载时初始化实例,线程安全但可能造成资源浪费。
- 懒汉式单例:首次使用时初始化,需加锁保证线程安全,但锁竞争影响性能。
- 双重检查锁定(DCL):通过
volatile和两次null检查优化性能,但需注意JVM重排序问题。
// 双重检查锁定单例
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
本节小结
- 单例模式性能优化需权衡线程安全和资源占用
- 简单场景可用枚举实现(Java)或静态初始化(C#)
第二章 常见模式对比
2.1 策略模式 vs if-else
问题场景:电商促销活动中,不同会员等级享受不同折扣(普通会员9折、银卡8.5折、金卡8折)。
if-else实现:
public decimal CalculateDiscount(MemberLevel level, decimal price) { switch (level) { case MemberLevel.Normal: return price * 0.9m; case MemberLevel.Silver: return price * 0.85m; case MemberLevel.Gold: return price * 0.8m; default: throw new ArgumentException(); } }- 缺点:新增会员等级需修改
CalculateDiscount方法,违反开闭原则。
- 缺点:新增会员等级需修改
策略模式实现:
public interface IDiscountStrategy { decimal ApplyDiscount(decimal price); } public class NormalDiscount : IDiscountStrategy { public decimal ApplyDiscount(decimal price) => price * 0.9m; } // 其他策略类省略... public class DiscountContext { private IDiscountStrategy _strategy; public DiscountContext(IDiscountStrategy strategy) => _strategy = strategy; public decimal Calculate(decimal price) => _strategy.ApplyDiscount(price); }- 优点:新增策略无需修改现有代码,符合开闭原则。
本节小结
- 策略模式将条件分支转化为对象,提升扩展性
- if-else适合简单、稳定的逻辑,策略模式适合复杂、多变的场景
2.2 装饰器模式 vs 继承
问题场景:为图形添加边框、阴影等装饰效果。
继承实现:
class Shape { void draw() { System.out.println("Shape"); } } class BorderShape extends Shape { @Override void draw() { System.out.print("Border-"); super.draw(); } } class ShadowShape extends Shape { @Override void draw() { System.out.print("Shadow-"); super.draw(); } }- 缺点:若需同时添加边框和阴影,需创建
BorderShadowShape子类,导致类爆炸。
- 缺点:若需同时添加边框和阴影,需创建
装饰器模式实现:
interface Shape { void draw(); } class ConcreteShape implements Shape { public void draw() { System.out.println("Shape"); } } abstract class ShapeDecorator implements Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; } public void draw() { decoratedShape.draw(); } } class BorderDecorator extends ShapeDecorator { public BorderDecorator(Shape decoratedShape) { super(decoratedShape); } @Override public void draw() { System.out.print("Border-"); super.draw(); } }- 优点:通过组合动态添加功能,避免类爆炸。
本节小结
- 装饰器模式通过对象组合实现功能扩展,符合开闭原则
- 继承通过类层次实现扩展,易导致刚性设计
2.3 观察者模式 vs 事件总线
问题场景:用户注册后,需同时发送邮件、短信和推送通知。
观察者模式实现:
public interface IObserver { void Update(string message); } public class EmailObserver : IObserver { public void Update(string message) => Console.WriteLine($"Email: {message}"); } // 其他观察者省略... public class UserService { private List<IObserver> _observers = new List<IObserver>(); public void Register(string username) { Console.WriteLine($"User {username} registered"); _observers.ForEach(o => o.Update($"User {username} registered")); } public void AddObserver(IObserver observer) => _observers.Add(observer); }- 优点:观察者与主题直接关联,耦合度低。
事件总线实现:
public static class EventBus { private static Dictionary<string, List<Action<string>>> _handlers = new Dictionary<string, List<Action<string>>>(); public static void Subscribe(string eventName, Action<string> handler) { if (!_handlers.ContainsKey(eventName)) _handlers[eventName] = new List<Action<string>>(); _handlers[eventName].Add(handler); } public static void Publish(string eventName, string message) { if (_handlers.TryGetValue(eventName, out var handlers)) { handlers.ForEach(h => h(message)); } } }- 优点:解耦发布者和订阅者,支持跨模块通信。
本节小结
- 观察者模式适合主题-观察者一对一/多对一场景
- 事件总线适合跨模块、动态订阅的复杂场景
第三章 选型原则与避坑
3.1 根据变化点选择模式
设计模式的核心目标是应对变化。选型时应遵循以下原则:
- 识别变化点:如算法、行为、结构等可能变化的部分。
- 隔离变化:通过模式将变化部分封装为独立对象。
- 复用不变部分:确保不变逻辑不被重复实现。
案例:电商系统中的支付方式(支付宝、微信、银联)可能变化,应使用策略模式隔离支付算法。
3.2 避免过度设计与滥用
过度使用设计模式会导致代码复杂度激增。常见误区:
单例模式滥用:将所有工具类设计为单例,导致线程安全问题。
// 错误示例:非线程安全的单例 public class Logger { private static Logger instance; private Logger() {} public static Logger getInstance() { if (instance == null) instance = new Logger(); // 非线程安全 return instance; } }- 正确做法:使用枚举实现单例(Java)或依赖注入(C#)。
观察者模式滥用:简单事件通知使用观察者模式,导致代码冗余。
// 简单事件通知无需观察者模式 public class UserService { public event Action<string> OnRegistered; public void Register(string username) { Console.WriteLine($"User {username} registered"); OnRegistered?.Invoke($"User {username} registered"); } }
本节小结
- 设计模式应服务于业务需求,而非技术炫耀
- 简单场景优先使用语言内置特性(如事件、枚举)
3.3 模式组合使用技巧
复杂场景常需组合多种模式。例如:
策略模式 + 工厂模式:动态选择支付策略。
public interface IPaymentStrategy { bool Pay(decimal amount); } public class AlipayStrategy : IPaymentStrategy { /* 实现 */ } public class PaymentFactory { public static IPaymentStrategy Create(string type) { return type switch { "alipay" => new AlipayStrategy(), "wechat" => new WechatPayStrategy(), _ => throw new ArgumentException() }; } }装饰器模式 + 组合模式:为图形添加复杂装饰效果。
interface Shape { void draw(); } class CompositeShape implements Shape { private List<Shape> _children = new ArrayList<>(); public void add(Shape shape) { _children.add(shape); } public void draw() { _children.forEach(Shape::draw); } } class BorderDecorator implements Shape { private Shape _shape; public BorderDecorator(Shape shape) { _shape = shape; } public void draw() { System.out.print("Border-"); _shape.draw(); } }
本节小结
- 模式组合可解决复杂问题,但需避免过度嵌套
- 优先使用组合替代继承,降低耦合度
课程总结
本课程通过对比扩展性、复杂度、性能等维度,结合策略模式、装饰器模式等常见模式的对比分析,总结了根据变化点选型、避免过度设计等核心原则。实际项目中应结合业务需求,灵活组合模式,避免生搬硬套。