通俗版23种设计模式解析
通俗版23种设计模式解析
一、创建型模式(造物主的智慧)
-
单例模式
- 核心:全局唯一实例(像公司CEO)
- 场景:配置管理器、数据库连接池
// C# 实现 public class ConfigManager {private static ConfigManager _instance = new ConfigManager();public static ConfigManager Instance => _instance;private ConfigManager() { } // 封锁new操作 }
-
工厂方法
- 核心:子类决定创建哪种对象(像汽车4S店)
- 场景:支付方式选择(支付宝/微信)
// Java 实现 interface Payment { void pay(); } class Alipay implements Payment { /*...*/ } class PaymentFactory {public Payment createPayment(String type) {if("alipay".equals(type)) return new Alipay();else throw new IllegalArgumentException();} }
-
抽象工厂
- 核心:创建产品家族(像宜家成套家具)
- 场景:跨平台UI组件库
// C# 实现 interface IButton { void Render(); } class WinButton : IButton { public void Render() => Console.WriteLine("Windows按钮"); } interface IUIFactory { IButton CreateButton(); } class WinFactory : IUIFactory { public IButton CreateButton() => new WinButton(); }
-
建造者
- 核心:分步组装复杂对象(像乐高拼装)
- 场景:构造HTTP请求
// Java 实现 class HttpRequest {private String method;public static class Builder {private HttpRequest request = new HttpRequest();public Builder setMethod(String m) { request.method = m; return this; }public HttpRequest build() { return request; }} } // 使用:new HttpRequest.Builder().setMethod("GET").build();
-
原型模式
- 核心:克隆现有对象(像复印机)
- 场景:游戏敌人复制
// C# 实现 class Enemy : ICloneable {public string Type { get; set; }public object Clone() => this.MemberwiseClone(); // 浅拷贝 }
二、结构型模式(组装的奥秘)
-
适配器
- 核心:接口转换器(像电源转接头)
- 场景:旧日志系统兼容
// Java 实现 interface NewLogger { void log(String msg); } class LegacyLogger { void writeLog(String s) { /*...*/ } } class LoggerAdapter implements NewLogger {private LegacyLogger adaptee = new LegacyLogger();public void log(String msg) { adaptee.writeLog(msg); } }
-
桥接模式
- 核心:抽象与实现解耦(像遥控器控制电视)
- 场景:跨平台图形渲染
// C# 实现 interface IRenderer { void DrawCircle(); } class VectorRenderer : IRenderer { /*...*/ } abstract class Shape {protected IRenderer renderer;protected Shape(IRenderer r) => renderer = r;public abstract void Draw(); } class Circle : Shape {public Circle(IRenderer r) : base(r) { }public override void Draw() => renderer.DrawCircle(); }
-
组合模式
- 核心:树形结构处理(像文件系统)
- 场景:组织架构管理
// Java 实现 interface Component { void display(); } class Employee implements Component { public void display() { /*...*/ } } class Department implements Component {private List<Component> children = new ArrayList<>();public void add(Component c) { children.add(c); }public void display() { children.forEach(Component::display); } }
-
装饰器
- 核心:动态添加功能(像给手机贴膜)
- 场景:数据流加密压缩
// C# 实现 interface IStream { void Write(string data); } class FileStream : IStream { /*...*/ } class CryptoStream : IStream {private IStream _inner;public CryptoStream(IStream inner) => _inner = inner;public void Write(string data) {string encrypted = Encrypt(data);_inner.Write(encrypted);} }
-
外观模式
- 核心:复杂系统统一入口(像酒店前台)
- 场景:一键启动计算机
// Java 实现 class CPU { void start() { /*...*/ } } class Memory { void load() { /*...*/ } } class ComputerFacade {private CPU cpu = new CPU();private Memory memory = new Memory();public void boot() { cpu.start(); memory.load(); } }
三、行为型模式(协作的艺术)
-
观察者模式
- 核心:状态变化通知(像微信公众号)
- 场景:股票价格提醒
// C# 实现 class Stock {private List<IObserver> _observers = new List<IObserver>();public void AddObserver(IObserver o) => _observers.Add(o);public void PriceChanged() {foreach(var o in _observers) o.Update();} }
-
策略模式
- 核心:算法自由切换(像出行导航策略)
- 场景:排序算法选择
// Java 实现 interface SortStrategy { void sort(int[] arr); } class QuickSort implements SortStrategy { /*...*/ } class Context {private SortStrategy strategy;public void setStrategy(SortStrategy s) { strategy = s; }public void executeSort(int[] arr) { strategy.sort(arr); } }
-
命令模式
- 核心:封装操作为对象(像餐厅点菜单)
- 场景:撤销/重做功能
// C# 实现 interface ICommand { void Execute(); void Undo(); } class AddTextCommand : ICommand {private Document _doc;private string _text;public void Execute() => _doc.AddText(_text);public void Undo() => _doc.RemoveText(_text.Length); }
-
状态模式
- 核心:行为随状态改变(像红绿灯)
- 场景:订单状态流转
// Java 实现 interface OrderState { void cancel(); } class ShippedState implements OrderState {public void cancel() { System.out.println("已发货订单无法取消"); } } class Order {private OrderState state;public void setState(OrderState s) { state = s; }public void cancel() { state.cancel(); } }
四、其他关键模式
- 责任链:请求传递链(像审批流程)
- 迭代器:统一遍历方式(像遥控器换台)
- 中介者:集中调度(像机场控制塔)
- 备忘录:状态快照(像游戏存档)
- 访问者:动态添加操作(像税务稽查员)
- 模板方法:算法骨架(像咖啡制作流程)
- 解释器:语法解析(像SQL解析器)
- 享元:对象复用(像字符共享池)
- 代理:控制访问(像房产中介)
模式选择速查表
问题类型 | 推荐模式 |
---|---|
全局访问点 | 单例模式 |
灵活创建对象 | 工厂方法/抽象工厂 |
分步构建复杂对象 | 建造者模式 |
接口不兼容 | 适配器模式 |
多维度扩展 | 桥接模式 |
树形结构处理 | 组合模式 |
动态添加功能 | 装饰器模式 |
简化复杂系统 | 外观模式 |
状态驱动行为 | 状态模式 |
算法自由切换 | 策略模式 |
事件通知机制 | 观察者模式 |
操作封装 | 命令模式 |
黄金法则:
- 优先组合而非继承
- 面向接口编程
- 高内聚低耦合
- 对修改关闭,对扩展开放(开闭原则)
实际案例:电商系统典型模式组合
- 支付模块:策略模式+工厂方法
- 订单管理:状态模式+观察者模式
- 商品展示:装饰器模式(价格修饰)
- 权限控制:代理模式
- 日志系统:责任链模式+适配器模式