行为型设计模式主要关注对象之间的职责分配和算法的封装,使对象之间能够更好地协作
// 抽象审批者
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)); // 经理处理
// 命令队列管理器
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();
// 终结符表达式:变量
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
// 自定义集合类
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
}
// 服务协调中介者
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());// 自动处理服务间流程
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() {
// 获取数据库当前状态快照
}
}
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("系统升级中"); // 输出:用户收到通知:系统升级中
// 状态接口
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(); // 发货操作
// 策略接口
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 元
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逗号分隔数据");
}
// 员工元素
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);