一文读懂设计模式行为型11种

行为型设计模式主要关注对象之间的职责分配和算法的封装,使对象之间能够更好地协作

  1. 责任链模式(Chain of Responsibility)
    核心思想:将请求沿着处理链传递,直到有一个处理者处理它。
    场景:审批流程、日志处理
    技术:Net core 管道机制
// 抽象审批者
public abstract class Approver {
    protected Approver _next;
    public void SetNext(Approver next) => _next = next;
    public abstract void ProcessRequest(LeaveRequest request);
}

// 具体处理者:组长
public class TeamLeader : Approver {
    public override void ProcessRequest(LeaveRequest request) {
        if (request.Days <= 3) 
            Console.WriteLine($"组长批准{request.Days}天请假");
        else _next?.ProcessRequest(request);
    }
}

// 客户端调用(网页2)
var chain = new TeamLeader()
    .SetNext(new Manager())
    .SetNext(new Director());
chain.ProcessRequest(new LeaveRequest(5)); // 经理处理
  1. 命令模式(Command)
    核心思想:将请求封装为对象,支持请求的排队、撤销与日志记录。
    场景:GUI操作、事务管理、异步执行批量文件操作
// 命令队列管理器
public class TaskScheduler {
    private readonly Queue<ICommand> _queue = new();

    public void AddCommand(ICommand cmd) => _queue.Enqueue(cmd);
    
    public void ProcessTasks() {
        while (_queue.Count > 0) {
            var cmd = _queue.Dequeue();
            cmd.Execute();
        }
    }
}

// 客户端调用
scheduler.AddCommand(new ZipCommand("logs"));
scheduler.AddCommand(new EncryptCommand("data"));
scheduler.ProcessTasks();
  1. 解释器模式(Interpreter)
    核心思想:定义语言的语法规则,并解释执行表达式
    场景:正则表达式解析、SQL查询
// 终结符表达式:变量
public class Variable : IExpression {
    private string _name;
    public Variable(string name) => _name = name;
    public int Interpret(Dictionary<string, int> context) => context[_name];
}

// 客户端调用
var context = new Dictionary<string, int> { {"x", 10}, {"y", 5} };
var expr = new Add(new Variable("x"), new Subtract(new Variable("y"), new Number(2)));
Console.WriteLine(expr.Interpret(context)); // 输出 13
  1. 迭代器模式(Iterator)
    核心思想:提供一种方法顺序访问聚合对象的元素,而无需暴露其内部表示。
    场景:集合遍历、数据库查询结果处理
// 自定义集合类
public class MyCollection : IEnumerable {
    private object[] _items = new object[5];
    
    public MyCollection() {
        for (int i = 0; i < 5; i++) 
            _items[i] = i;
    }

    public IEnumerator GetEnumerator() {
        return new MyIterator(_items);
    }
}

// 自定义迭代器
public class MyIterator : IEnumerator {
    private object[] _items;
    private int _position = -1;
    
    public MyIterator(object[] items) => _items = items;
    
    public object Current => _items[_position];
    public bool MoveNext() => ++_position < _items.Length;
    public void Reset() => _position = -1;
}

// 客户端调用
foreach (int item in new MyCollection()) {
    Console.WriteLine(item); // 输出0-4
}
  1. 中介者模式(Mediator)
    核心思想:通过中介对象协调多个对象间的交互,降低耦合度。
    场景:聊天室、UI组件通信、微服务协调通信
// 服务协调中介者
public class OrderMediator : IServiceMediator {
    public void ProcessOrder(Order order) {
        try {
            InventoryService.ReserveStock(order);
            PaymentService.Charge(order);
            OrderService.Confirm(order);
        } catch {
            InventoryService.Rollback(order);
            PaymentService.Refund(order);
        }
    }
}

// 客户端调用
_mediator.ProcessOrder(new Order());// 自动处理服务间流程
  1. 备忘录模式(Memento)
    核心思想:捕获对象状态并在需要时恢复
    场景:撤销操作、游戏存档、数据库事务回滚
public class TransactionManager {
    private Stack<TransactionMemento> _log = new();
    
    public void BeginTransaction() {
        _log.Clear();
        _log.Push(GetCurrentState());
    }
    
    public void Commit() => _log.Clear();
    
    public void Rollback() {
        while (_log.Count > 1) {
            var memento = _log.Pop();
            ApplyReverseOperation(memento);
        }
    }
    
    private TransactionMemento GetCurrentState() {
        // 获取数据库当前状态快照
    }
}
  1. 观察者模式(Observer) 发布订阅
    核心思想:定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者自动收到通知。
    场景:事件处理、实时数据推送
public interface IObserver
{
    void Update(string message);
}

public class Subject
{
    private List<IObserver> observers = new List<IObserver>();
    public void Attach(IObserver observer) => observers.Add(observer);
    public void Notify(string message)
    {
        foreach (var observer in observers)
            observer.Update(message);
    }
}

public class User : IObserver
{
    public void Update(string message) => Console.WriteLine($"用户收到通知:{message}");
}

// 使用
var subject = new Subject();
subject.Attach(new User());
subject.Notify("系统升级中"); // 输出:用户收到通知:系统升级中
  1. 状态模式(State)
    核心思想:允许对象在其内部状态改变时改变行为
    场景:订单状态机、游戏角色行为切换
// 状态接口
public interface IOrderState {
    void Pay(Order order);
    void Ship(Order order);
    void Cancel(Order order);
}

// 待支付状态
public class PendingState : IOrderState {
    public void Pay(Order order) {
        order.State = new PaidState();
        Console.WriteLine("订单支付成功");
    }
    public void Ship(Order _) => Console.WriteLine("需先支付才能发货");
    public void Cancel(Order order) {
        order.State = new CancelledState();
        Console.WriteLine("订单已取消");
    }
}

// 上下文类
public class Order {
    public IOrderState State { get; set; } = new PendingState();
    
    public void Pay() => State.Pay(this);
    public void Ship() => State.Ship(this);
    public void Cancel() => State.Cancel(this);
}

// 调用示例
var order = new Order();
order.Pay();  // 状态变为PaidState
order.Ship(); // 发货操作
  1. 策略模式(Strategy)
    核心思想:定义一系列算法,使其可以相互替换,且算法的变化独立于客户端。
    场景:支付方式选择、排序算法切换
// 策略接口
public interface IPaymentStrategy {
    void ProcessPayment(decimal amount);
}

// 微信支付策略
public class WeChatPayStrategy : IPaymentStrategy {
    public void ProcessPayment(decimal amount) {
        Console.WriteLine($"微信支付:{amount} 元");
    }
}

// 支付宝策略
public class AlipayStrategy : IPaymentStrategy {
    public void ProcessPayment(decimal amount) {
        Console.WriteLine($"支付宝支付:{amount} 元");
    }
}

// 上下文类
public class PaymentContext {
    private IPaymentStrategy _strategy;
    
    public void SetStrategy(IPaymentStrategy strategy) {
        _strategy = strategy;
    }
    
    public void ExecutePayment(decimal amount) {
        _strategy.ProcessPayment(amount);
    }
}

// 调用示例
var context = new PaymentContext();
context.SetStrategy(new WeChatPayStrategy());
context.ExecutePayment(100);  // 微信支付:100 元
context.SetStrategy(new AlipayStrategy());
context.ExecutePayment(200); // 支付宝支付:200 元
  1. 模板方法模式(Template Method)
    核心思想:在抽象类中定义算法骨架,将某些步骤延迟到子类实现
    场景:框架设计、流程标准化、文件处理流程统一处理不同格式文件(CSV/JSON/XML)的读取流程
public abstract class FileProcessor {
    public void ProcessFile(string path) {
        OpenFile(path);
        ParseContent();
        ConvertData();
        CloseFile();
    }
    
    protected virtual void OpenFile(string path) => Console.WriteLine($"打开文件: {path}");
    protected abstract void ParseContent();
    protected virtual void ConvertData() => Console.WriteLine("默认数据转换");
    protected virtual void CloseFile() => Console.WriteLine("关闭文件");
}

public class CsvProcessor : FileProcessor {
    protected override void ParseContent() => Console.WriteLine("解析CSV逗号分隔数据");
}
  1. 访问者模式(Visitor)
    核心思想:将算法与对象结构分离,支持在不修改对象结构的前提下添加新操作。
    场景:文档处理、编译器语法树分析、为不同职级员工(经理、董事长)动态添加薪资查询功能
// 员工元素
public abstract class Employee {
    public string Name { get; set; }
    public abstract void Accept(IVisitor visitor);
}

// 具体员工类型
public class Manager : Employee {
    public override void Accept(IVisitor visitor) => visitor.Visit(this);
}

// 薪资访问者
public class SalaryVisitor : IVisitor {
    public void Visit(Manager m) => 
        Console.WriteLine($"{m.Name}薪资:100000");
    public void Visit(Chairman c) => 
        Console.WriteLine($"{c.Name}薪资:1000000");
}

// 调用示例
Employee[] staff = { new Manager("张总"), new Chairman("李董") };
var salaryVisitor = new SalaryVisitor();
foreach(var emp in staff) emp.Accept(salaryVisitor);

一文读懂设计模式行为型11种_第1张图片

你可能感兴趣的:(程序思想-设计模式与设计原则,设计模式)