C# 23种模式具体应用场景

整理23种设计模式的应用场景并提供完整具体的Demo是一个相当庞大的任务。为了确保每个模式的解释和示例都清晰易懂,我将逐步介绍每个设计模式,并提供相应的C#代码示例和中文注释。

1. 单例模式(Singleton Pattern)

应用场景

在一个Web应用中,我们可能需要一个全局的配置管理器来读取配置文件,并确保在整个应用生命周期中只有一个实例。

示例代码

using System;

public class ConfigurationManager
{
    private static ConfigurationManager _instance;
    private static readonly object _lock = new object();

    // 私有构造函数,防止外部实例化
    private ConfigurationManager()
    {
        // 读取配置文件
        Console.WriteLine("读取配置文件...");
    }

    public static ConfigurationManager Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new ConfigurationManager();
                    }
                }
            }
            return _instance;
        }
    }

    public string GetConfig(string key)
    {
        // 返回配置值
        return "配置值";
    }
}

class Program
{
    static void Main(string[] args)
    {
        ConfigurationManager configManager = ConfigurationManager.Instance;
        string configValue = configManager.GetConfig("SomeKey");
        Console.WriteLine(configValue);
    }
}

2. 工厂方法模式(Factory Method Pattern)

应用场景

在一个电商系统中,我们可能需要根据不同的支付方式(如支付宝、微信支付、信用卡支付)创建不同的支付处理对象。

示例代码

using System;

public abstract class Payment
{
    public abstract void Pay();
}

public class Alipay : Payment
{
    public override void Pay()
    {
        Console.WriteLine("使用支付宝支付");
    }
}

public class WeChatPay : Payment
{
    public override void Pay()
    {
        Console.WriteLine("使用微信支付");
    }
}

public abstract class PaymentFactory
{
    public abstract Payment CreatePayment();
}

public class AlipayFactory : PaymentFactory
{
    public override Payment CreatePayment()
    {
        return new Alipay();
    }
}

public class WeChatPayFactory : PaymentFactory
{
    public override Payment CreatePayment()
    {
        return new WeChatPay();
    }
}

class Program
{
    static void Main(string[] args)
    {
        PaymentFactory factory = new AlipayFactory();
        Payment payment = factory.CreatePayment();
        payment.Pay();

        factory = new WeChatPayFactory();
        payment = factory.CreatePayment();
        payment.Pay();
    }
}

3. 抽象工厂模式(Abstract Factory Pattern)

应用场景

在一个跨平台的GUI应用中,我们可能需要为不同的操作系统(如Windows、MacOS)创建不同的UI组件(如按钮、文本框)。

示例代码

using System;

public interface IButton
{
    void Render();
}

public interface ITextBox
{
    void Render();
}

public class WindowsButton : IButton
{
    public void Render()
    {
        Console.WriteLine("渲染Windows按钮");
    }
}

public class MacOSButton : IButton
{
    public void Render()
    {
        Console.WriteLine("渲染MacOS按钮");
    }
}

public class WindowsTextBox : ITextBox
{
    public void Render()
    {
        Console.WriteLine("渲染Windows文本框");
    }
}

public class MacOSTextBox : ITextBox
{
    public void Render()
    {
        Console.WriteLine("渲染MacOS文本框");
    }
}

public interface IGUIFactory
{
    IButton CreateButton();
    ITextBox CreateTextBox();
}

public class WindowsFactory : IGUIFactory
{
    public IButton CreateButton()
    {
        return new WindowsButton();
    }

    public ITextBox CreateTextBox()
    {
        return new WindowsTextBox();
    }
}

public class MacOSFactory : IGUIFactory
{
    public IButton CreateButton()
    {
        return new MacOSButton();
    }

    public ITextBox CreateTextBox()
    {
        return new MacOSTextBox();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IGUIFactory factory = new WindowsFactory();
        IButton button = factory.CreateButton();
        ITextBox textBox = factory.CreateTextBox();
        button.Render();
        textBox.Render();

        factory = new MacOSFactory();
        button = factory.CreateButton();
        textBox = factory.CreateTextBox();
        button.Render();
        textBox.Render();
    }
}

4. 建造者模式(Builder Pattern)

应用场景

在一个复杂对象的创建过程中,例如创建一个包含多个部分的报告(标题、内容、页脚),我们可以使用建造者模式来一步一步构建这个对象。

示例代码

using System;

public class Report
{
    public string Title { get; set; }
    public string Content { get; set; }
    public string Footer { get; set; }

    public void Show()
    {
        Console.WriteLine($"标题: {Title}");
        Console.WriteLine($"内容: {Content}");
        Console.WriteLine($"页脚: {Footer}");
    }
}

public abstract class ReportBuilder
{
    protected Report report = new Report();

    public abstract void BuildTitle();
    public abstract void BuildContent();
    public abstract void BuildFooter();

    public Report GetReport()
    {
        return report;
    }
}

public class PDFReportBuilder : ReportBuilder
{
    public override void BuildTitle()
    {
        report.Title = "PDF 报告标题";
    }

    public override void BuildContent()
    {
        report.Content = "PDF 报告内容";
    }

    public override void BuildFooter()
    {
        report.Footer = "PDF 报告页脚";
    }
}

public class WordReportBuilder : ReportBuilder
{
    public override void BuildTitle()
    {
        report.Title = "Word 报告标题";
    }

    public override void BuildContent()
    {
        report.Content = "Word 报告内容";
    }

    public override void BuildFooter()
    {
        report.Footer = "Word 报告页脚";
    }
}

public class ReportDirector
{
    private ReportBuilder builder;

    public ReportDirector(ReportBuilder builder)
    {
        this.builder = builder;
    }

    public void Construct()
    {
        builder.BuildTitle();
        builder.BuildContent();
        builder.BuildFooter();
    }
}

class Program
{
    static void Main(string[] args)
    {
        ReportBuilder builder = new PDFReportBuilder();
        ReportDirector director = new ReportDirector(builder);
        director.Construct();
        Report report = builder.GetReport();
        report.Show();

        builder = new WordReportBuilder();
        director = new ReportDirector(builder);
        director.Construct();
        report = builder.GetReport();
        report.Show();
    }
}

5. 原型模式(Prototype Pattern)

应用场景

在一个图形编辑器中,我们可能需要复制图形对象(如圆形、矩形),并对其进行修改。使用原型模式可以方便地复制这些对象。

示例代码

using System;

public abstract class Shape
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Color { get; set; }

    public abstract Shape Clone();
}

public class Circle : Shape
{
    public int Radius { get; set; }

    public override Shape Clone()
    {
        return (Shape)this.MemberwiseClone();
    }
}

public class Rectangle : Shape
{
    public int Width { get; set; }
    public int Height { get; set; }

    public override Shape Clone()
    {
        return (Shape)this.MemberwiseClone();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Circle circle = new Circle { X = 10, Y = 20, Color = "Red", Radius = 15 };
        Circle clonedCircle = (Circle)circle.Clone();
        Console.WriteLine($"克隆的圆形: X={clonedCircle.X}, Y={clonedCircle.Y}, Color={clonedCircle.Color}, Radius={clonedCircle.Radius}");

        Rectangle rectangle = new Rectangle { X = 30, Y = 40, Color = "Blue", Width = 50, Height = 60 };
        Rectangle clonedRectangle = (Rectangle)rectangle.Clone();
        Console.WriteLine($"克隆的矩形: X={clonedRectangle.X}, Y={clonedRectangle.Y}, Color={clonedRectangle.Color}, Width={clonedRectangle.Width}, Height={clonedRectangle.Height}");
    }
}

以上是前五种设计模式的应用场景和示例代码。由于篇幅限制,其他设计模式的示例可以在后续继续补充。如果你有特定的设计模式需要优先了解,请告诉我,我会优先提供相关示例。

6.适配器模式(Adapter Pattern)

应用场景:假设我们有一个旧的支付系统 OldPaymentSystem,它有一个方法 ProcessPayment。现在我们有一个新的支付系统 NewPaymentSystem,它有一个方法 MakePayment。我们希望在不修改旧系统的情况下使用新系统。

// 旧的支付系统
public class OldPaymentSystem
{
    public void ProcessPayment(string paymentDetails)
    {
        Console.WriteLine($"Processing payment using old system: {paymentDetails}");
    }
}

// 新的支付系统
public class NewPaymentSystem
{
    public void MakePayment(string paymentDetails)
    {
        Console.WriteLine($"Processing payment using new system: {paymentDetails}");
    }
}

// 适配器
public class PaymentAdapter : OldPaymentSystem
{
    private readonly NewPaymentSystem _newPaymentSystem;

    public PaymentAdapter(NewPaymentSystem newPaymentSystem)
    {
        _newPaymentSystem = newPaymentSystem;
    }

    public new void ProcessPayment(string paymentDetails)
    {
        _newPaymentSystem.MakePayment(paymentDetails);
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        OldPaymentSystem oldPaymentSystem = new PaymentAdapter(new NewPaymentSystem());
        oldPaymentSystem.ProcessPayment("100 USD");
    }
}

7. 装饰器模式(Decorator Pattern)

应用场景:假设我们有一个基本的 Coffee 类,并且我们希望动态地添加不同的配料(如牛奶、糖等)来装饰咖啡。

// 基本的咖啡接口
public interface ICoffee
{
    string GetDescription();
    double GetCost();
}

// 基本的咖啡实现
public class SimpleCoffee : ICoffee
{
    public string GetDescription()
    {
        return "Simple Coffee";
    }

    public double GetCost()
    {
        return 5.0;
    }
}

// 装饰器基类
public abstract class CoffeeDecorator : ICoffee
{
    protected ICoffee _coffee;

    public CoffeeDecorator(ICoffee coffee)
    {
        _coffee = coffee;
    }

    public virtual string GetDescription()
    {
        return _coffee.GetDescription();
    }

    public virtual double GetCost()
    {
        return _coffee.GetCost();
    }
}

// 牛奶装饰器
public class MilkDecorator : CoffeeDecorator
{
    public MilkDecorator(ICoffee coffee) : base(coffee) { }

    public override string GetDescription()
    {
        return _coffee.GetDescription() + ", Milk";
    }

    public override double GetCost()
    {
        return _coffee.GetCost() + 1.5;
    }
}

// 糖装饰器
public class SugarDecorator : CoffeeDecorator
{
    public SugarDecorator(ICoffee coffee) : base(coffee) { }

    public override string GetDescription()
    {
        return _coffee.GetDescription() + ", Sugar";
    }

    public override double GetCost()
    {
        return _coffee.GetCost() + 0.5;
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        ICoffee coffee = new SimpleCoffee();
        Console.WriteLine($"{coffee.GetDescription()} : ${coffee.GetCost()}");

        coffee = new MilkDecorator(coffee);
        Console.WriteLine($"{coffee.GetDescription()} : ${coffee.GetCost()}");

        coffee = new SugarDecorator(coffee);
        Console.WriteLine($"{coffee.GetDescription()} : ${coffee.GetCost()}");
    }
}

8. 观察者模式(Observer Pattern)

应用场景:假设我们有一个股票市场系统,当股票价格变化时,所有订阅者(如投资者)都会收到通知。

using System;
using System.Collections.Generic;

// 观察者接口
public interface IObserver
{
    void Update(string stockSymbol, double stockPrice);
}

// 被观察者接口
public interface ISubject
{
    void RegisterObserver(IObserver observer);
    void RemoveObserver(IObserver observer);
    void NotifyObservers();
}

// 股票市场
public class StockMarket : ISubject
{
    private readonly List<IObserver> _observers;
    private readonly Dictionary<string, double> _stocks;

    public StockMarket()
    {
        _observers = new List<IObserver>();
        _stocks = new Dictionary<string, double>();
    }

    public void RegisterObserver(IObserver observer)
    {
        _observers.Add(observer);
    }

    public void RemoveObserver(IObserver observer)
    {
        _observers.Remove(observer);
    }

    public void NotifyObservers()
    {
        foreach (var observer in _observers)
        {
            foreach (var stock in _stocks)
            {
                observer.Update(stock.Key, stock.Value);
            }
        }
    }

    public void SetStockPrice(string stockSymbol, double stockPrice)
    {
        _stocks[stockSymbol] = stockPrice;
        NotifyObservers();
    }
}

// 投资者
public class Investor : IObserver
{
    private readonly string _name;

    public Investor(string name)
    {
        _name = name;
    }

    public void Update(string stockSymbol, double stockPrice)
    {
        Console.WriteLine($"Investor {_name} notified. Stock: {stockSymbol}, New Price: {stockPrice}");
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        StockMarket stockMarket = new StockMarket();

        Investor investor1 = new Investor("Alice");
        Investor investor2 = new Investor("Bob");

        stockMarket.RegisterObserver(investor1);
        stockMarket.RegisterObserver(investor2);

        stockMarket.SetStockPrice("AAPL", 150.0);
        stockMarket.SetStockPrice("GOOGL", 2800.0);
    }
}

9. 策略模式(Strategy Pattern)

应用场景:假设我们有一个支付系统,可以使用不同的支付方式(如信用卡、PayPal、比特币等)。我们希望能够动态地选择支付方式。

// 支付策略接口
public interface IPaymentStrategy
{
    void Pay(double amount);
}

// 信用卡支付策略
public class CreditCardPayment : IPaymentStrategy
{
    public void Pay(double amount)
    {
        Console.WriteLine($"Paid {amount} using Credit Card.");
    }
}

// PayPal支付策略
public class PayPalPayment : IPaymentStrategy
{
    public void Pay(double amount)
    {
        Console.WriteLine($"Paid {amount} using PayPal.");
    }
}

// 比特币支付策略
public class BitcoinPayment : IPaymentStrategy
{
    public void Pay(double amount)
    {
        Console.WriteLine($"Paid {amount} using Bitcoin.");
    }
}

// 支付上下文
public class PaymentContext
{
    private IPaymentStrategy _paymentStrategy;

    public void SetPaymentStrategy(IPaymentStrategy paymentStrategy)
    {
        _paymentStrategy = paymentStrategy;
    }

    public void Pay(double amount)
    {
        _paymentStrategy.Pay(amount);
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        PaymentContext paymentContext = new PaymentContext();

        paymentContext.SetPaymentStrategy(new CreditCardPayment());
        paymentContext.Pay(100.0);

        paymentContext.SetPaymentStrategy(new PayPalPayment());
        paymentContext.Pay(200.0);

        paymentContext.SetPaymentStrategy(new BitcoinPayment());
        paymentContext.Pay(300.0);
    }
}

10. 责任链模式(Chain of Responsibility Pattern)

应用场景:假设我们有一个客户服务系统,客户的请求可以是简单的查询、投诉或退款请求。我们希望不同的请求由不同的处理器处理。

// 请求类
public class Request
{
    public string RequestType { get; set; }
    public string RequestContent { get; set; }
}

// 处理器抽象类
public abstract class Handler
{
    protected Handler _nextHandler;

    public void SetNextHandler(Handler nextHandler)
    {
        _nextHandler = nextHandler;
    }

    public abstract void HandleRequest(Request request);
}

// 查询处理器
public class QueryHandler : Handler
{
    public override void HandleRequest(Request request)
    {
        if (request.RequestType == "Query")
        {
            Console.WriteLine($"Handling query: {request.RequestContent}");
        }
        else if (_nextHandler != null)
        {
            _nextHandler.HandleRequest(request);
        }
    }
}

// 投诉处理器
public class ComplaintHandler : Handler
{
    public override void HandleRequest(Request request)
    {
        if (request.RequestType == "Complaint")
        {
            Console.WriteLine($"Handling complaint: {request.RequestContent}");
        }
        else if (_nextHandler != null)
        {
            _nextHandler.HandleRequest(request);
        }
    }
}

// 退款处理器
public class RefundHandler : Handler
{
    public override void HandleRequest(Request request)
    {
        if (request.RequestType == "Refund")
        {
            Console.WriteLine($"Handling refund: {request.RequestContent}");
        }
        else if (_nextHandler != null)
        {
            _nextHandler.HandleRequest(request);
        }
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        Handler queryHandler = new QueryHandler();
        Handler complaintHandler = new ComplaintHandler();
        Handler refundHandler = new RefundHandler();

        queryHandler.SetNextHandler(complaintHandler);
        complaintHandler.SetNextHandler(refundHandler);

        Request request1 = new Request { RequestType = "Query", RequestContent = "What is my account balance?" };
        Request request2 = new Request { RequestType = "Complaint", RequestContent = "I have a complaint about a transaction." };
        Request request3 = new Request { RequestType = "Refund", RequestContent = "I want a refund for my purchase." };

        queryHandler.HandleRequest(request1);
        queryHandler.HandleRequest(request2);
        queryHandler.HandleRequest(request3);
    }
}

11. 命令模式(Command Pattern)

应用场景:假设我们有一个智能家居系统,可以控制灯光、空调和电视。我们希望能够通过命令模式来实现这些设备的控制。

// 命令接口
public interface ICommand
{
    void Execute();
}

// 具体命令类
public class LightOnCommand : ICommand
{
    private readonly Light _light;

    public LightOnCommand(Light light)
    {
        _light = light;
    }

    public void Execute()
    {
        _light.On();
    }
}

public class LightOffCommand : ICommand
{
    private readonly Light _light;

    public LightOffCommand(Light light)
    {
        _light = light;
    }

    public void Execute()
    {
        _light.Off();
    }
}

// 接收者类
public class Light
{
    public void On()
    {
        Console.WriteLine("Light is On");
    }

    public void Off()
    {
        Console.WriteLine("Light is Off");
    }
}

// 调用者类
public class RemoteControl
{
    private ICommand _command;

    public void SetCommand(ICommand command)
    {
        _command = command;
    }

    public void PressButton()
    {
        _command.Execute();
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        Light livingRoomLight = new Light();
        ICommand lightOn = new LightOnCommand(livingRoomLight);
        ICommand lightOff = new LightOffCommand(livingRoomLight);

        RemoteControl remote = new RemoteControl();

        remote.SetCommand(lightOn);
        remote.PressButton();

        remote.SetCommand(lightOff);
        remote.PressButton();
    }
}

12. 迭代器模式(Iterator Pattern)

应用场景:假设我们有一个图书馆系统,图书馆有多个书架,每个书架上有多本书。我们希望能够遍历每个书架上的书。

using System.Collections;

// 书类
public class Book
{
    public string Title { get; set; }

    public Book(string title)
    {
        Title = title;
    }
}

// 书架类
public class Bookshelf : IEnumerable<Book>
{
    private readonly List<Book> _books = new List<Book>();

    public void AddBook(Book book)
    {
        _books.Add(book);
    }

    public IEnumerator<Book> GetEnumerator()
    {
        return _books.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        Bookshelf bookshelf = new Bookshelf();
        bookshelf.AddBook(new Book("Book 1"));
        bookshelf.AddBook(new Book("Book 2"));
        bookshelf.AddBook(new Book("Book 3"));

        foreach (var book in bookshelf)
        {
            Console.WriteLine(book.Title);
        }
    }
}

13. 中介者模式(Mediator Pattern)

应用场景:假设我们有一个聊天室系统,用户可以发送消息给其他用户。我们希望通过中介者模式来管理用户之间的通信。

using System.Collections.Generic;

// 中介者接口
public interface IChatRoomMediator
{
    void SendMessage(string message, User user);
    void AddUser(User user);
}

// 具体中介者类
public class ChatRoom : IChatRoomMediator
{
    private readonly List<User> _users = new List<User>();

    public void AddUser(User user)
    {
        _users.Add(user);
    }

    public void SendMessage(string message, User user)
    {
        foreach (var u in _users)
        {
            if (u != user)
            {
                u.Receive(message);
            }
        }
    }
}

// 用户类
public class User
{
    private readonly IChatRoomMediator _chatRoom;
    public string Name { get; }

    public User(string name, IChatRoomMediator chatRoom)
    {
        Name = name;
        _chatRoom = chatRoom;
    }

    public void Send(string message)
    {
        Console.WriteLine($"{Name} sends: {message}");
        _chatRoom.SendMessage(message, this);
    }

    public void Receive(string message)
    {
        Console.WriteLine($"{Name} receives: {message}");
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        IChatRoomMediator chatRoom = new ChatRoom();

        User user1 = new User("Alice", chatRoom);
        User user2 = new User("Bob", chatRoom);
        User user3 = new User("Charlie", chatRoom);

        chatRoom.AddUser(user1);
        chatRoom.AddUser(user2);
        chatRoom.AddUser(user3);

        user1.Send("Hello, everyone!");
        user2.Send("Hi, Alice!");
    }
}

14. 备忘录模式(Memento Pattern)

应用场景:假设我们有一个文本编辑器,用户可以输入文本并且可以撤销操作。我们希望通过备忘录模式来实现撤销功能。

// 备忘录类
public class Memento
{
    public string State { get; }

    public Memento(string state)
    {
        State = state;
    }
}

// 发起人类
public class TextEditor
{
    public string Text { get; set; }

    public Memento Save()
    {
        return new Memento(Text);
    }

    public void Restore(Memento memento)
    {
        Text = memento.State;
    }
}

// 管理者类
public class Caretaker
{
    private readonly Stack<Memento> _mementos = new Stack<Memento>();

    public void SaveState(TextEditor editor)
    {
        _mementos.Push(editor.Save());
    }

    public void Undo(TextEditor editor)
    {
        if (_mementos.Count > 0)
        {
            editor.Restore(_mementos.Pop());
        }
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        TextEditor editor = new TextEditor();
        Caretaker caretaker = new Caretaker();

        editor.Text = "Hello, World!";
        caretaker.SaveState(editor);

        editor.Text = "Hello, Design Patterns!";
        caretaker.SaveState(editor);

        editor.Text = "Hello, Memento!";
        Console.WriteLine($"Current Text: {editor.Text}");

        caretaker.Undo(editor);
        Console.WriteLine($"After Undo: {editor.Text}");

        caretaker.Undo(editor);
        Console.WriteLine($"After Undo: {editor.Text}");
    }
}

15. 代理模式(Proxy Pattern)

应用场景:在访问某些资源时需要进行权限控制或延迟加载。例如,访问一个远程服务时,可以使用代理模式来控制访问。

// 代理模式示例代码
using System;

namespace ProxyPattern
{
    // 抽象主题
    public interface ISubject
    {
        void Request();
    }

    // 真实主题
    public class RealSubject : ISubject
    {
        public void Request()
        {
            Console.WriteLine("真实主题的请求处理。");
        }
    }

    // 代理
    public class Proxy : ISubject
    {
        private RealSubject _realSubject;

        public void Request()
        {
            if (_realSubject == null)
            {
                _realSubject = new RealSubject();
            }
            Console.WriteLine("代理处理前的操作。");
            _realSubject.Request();
            Console.WriteLine("代理处理后的操作。");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ISubject proxy = new Proxy();
            proxy.Request();
        }
    }
}

16. 组合模式(Composite Pattern)

应用场景:用于表示对象的部分-整体层次结构。例如,文件系统中的文件和文件夹。

// 组合模式示例代码
using System;
using System.Collections.Generic;

namespace CompositePattern
{
    // 组件
    public abstract class Component
    {
        protected string name;

        public Component(string name)
        {
            this.name = name;
        }

        public abstract void Display(int depth);
    }

    // 叶子
    public class Leaf : Component
    {
        public Leaf(string name) : base(name) { }

        public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + name);
        }
    }

    // 组合
    public class Composite : Component
    {
        private List<Component> children = new List<Component>();

        public Composite(string name) : base(name) { }

        public void Add(Component component)
        {
            children.Add(component);
        }

        public void Remove(Component component)
        {
            children.Remove(component);
        }

        public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + name);
            foreach (Component component in children)
            {
                component.Display(depth + 2);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));

            root.Add(comp);
            root.Add(new Leaf("Leaf C"));

            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);

            root.Display(1);
        }
    }
}

17. 享元模式(Flyweight Pattern)

应用场景:用于减少创建对象的数量,以减少内存占用和提高性能。例如,文本编辑器中的字符对象。

// 享元模式示例代码
using System;
using System.Collections.Generic;

namespace FlyweightPattern
{
    // 享元接口
    public interface IFlyweight
    {
        void Operation(int extrinsicState);
    }

    // 具体享元
    public class ConcreteFlyweight : IFlyweight
    {
        private string intrinsicState;

        public ConcreteFlyweight(string intrinsicState)
        {
            this.intrinsicState = intrinsicState;
        }

        public void Operation(int extrinsicState)
        {
            Console.WriteLine($"具体享元:内部状态 {intrinsicState},外部状态 {extrinsicState}");
        }
    }

    // 享元工厂
    public class FlyweightFactory
    {
        private Dictionary<string, IFlyweight> flyweights = new Dictionary<string, IFlyweight>();

        public IFlyweight GetFlyweight(string key)
        {
            if (!flyweights.ContainsKey(key))
            {
                flyweights[key] = new ConcreteFlyweight(key);
            }
            return flyweights[key];
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            FlyweightFactory factory = new FlyweightFactory();

            IFlyweight flyweight1 = factory.GetFlyweight("A");
            flyweight1.Operation(1);

            IFlyweight flyweight2 = factory.GetFlyweight("B");
            flyweight2.Operation(2);

            IFlyweight flyweight3 = factory.GetFlyweight("A");
            flyweight3.Operation(3);
        }
    }
}

18. 解释器模式(Interpreter Pattern)

应用场景:用于描述如何为语言定义一个文法,以及如何解析这个文法。例如,计算器程序中的表达式解析。

// 解释器模式示例代码
using System;
using System.Collections.Generic;

namespace InterpreterPattern
{
    // 抽象表达式
    public abstract class Expression
    {
        public abstract int Interpret(Dictionary<string, int> context);
    }

    // 终结符表达式
    public class NumberExpression : Expression
    {
        private int number;

        public NumberExpression(int number)
        {
            this.number = number;
        }

        public override int Interpret(Dictionary<string, int> context)
        {
            return number;
        }
    }

    // 非终结符表达式
    public class AddExpression : Expression
    {
        private Expression leftExpression;
        private Expression rightExpression;

        public AddExpression(Expression left, Expression right)
        {
            leftExpression = left;
            rightExpression = right;
        }

        public override int Interpret(Dictionary<string, int> context)
        {
            return leftExpression.Interpret(context) + rightExpression.Interpret(context);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> context = new Dictionary<string, int>();

            Expression expression = new AddExpression(new NumberExpression(5), new NumberExpression(10));
            int result = expression.Interpret(context);

            Console.WriteLine($"结果:{result}");
        }
    }
}

19. 访问者模式(Visitor Pattern)

应用场景:用于将操作分离到对象结构之外。例如,文件系统中的文件和文件夹可以接受不同的操作,如压缩、加密等。

// 访问者模式示例代码
using System;
using System.Collections.Generic;

namespace VisitorPattern
{
    // 访问者接口
    public interface IVisitor
    {
        void Visit(ElementA elementA);
        void Visit(ElementB elementB);
    }

    // 具体访问者
    public class ConcreteVisitor : IVisitor
    {
        public void Visit(ElementA elementA)
        {
            Console.WriteLine("访问元素A");
        }

        public void Visit(ElementB elementB)
        {
            Console.WriteLine("访问元素B");
        }
    }

    // 元素接口
    public abstract class Element
    {
        public abstract void Accept(IVisitor visitor);
    }

    // 具体元素A
    public class ElementA : Element
    {
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    // 具体元素B
    public class ElementB : Element
    {
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Element> elements = new List<Element>
            {
                new ElementA(),
                new ElementB()
            };

            IVisitor visitor = new ConcreteVisitor();

            foreach (Element element in elements)
            {
                element.Accept(visitor);
            }
        }
    }
}

20. 桥接模式(Bridge Pattern)

应用场景:假设我们有一个图形绘制应用程序,支持不同的形状(如圆形和矩形)和不同的绘制API(如OpenGL和DirectX)。桥接模式可以帮助我们将形状和绘制API解耦,使得它们可以独立变化。

// 实现部分接口
public interface IDrawAPI
{
    void DrawCircle(int radius, int x, int y);
}

// 具体实现类
public class OpenGLAPI : IDrawAPI
{
    public void DrawCircle(int radius, int x, int y)
    {
        Console.WriteLine($"OpenGLAPI: Drawing Circle [radius: {radius}, x: {x}, y: {y}]");
    }
}

public class DirectXAPI : IDrawAPI
{
    public void DrawCircle(int radius, int x, int y)
    {
        Console.WriteLine($"DirectXAPI: Drawing Circle [radius: {radius}, x: {x}, y: {y}]");
    }
}

// 抽象部分
public abstract class Shape
{
    protected IDrawAPI drawAPI;

    protected Shape(IDrawAPI drawAPI)
    {
        this.drawAPI = drawAPI;
    }

    public abstract void Draw();
}

// 扩展抽象部分
public class Circle : Shape
{
    private int x, y, radius;

    public Circle(int x, int y, int radius, IDrawAPI drawAPI) : base(drawAPI)
    {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public override void Draw()
    {
        drawAPI.DrawCircle(radius, x, y);
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        Shape redCircle = new Circle(100, 100, 10, new OpenGLAPI());
        Shape greenCircle = new Circle(100, 100, 10, new DirectXAPI());

        redCircle.Draw();
        greenCircle.Draw();
    }
}

21. 模板方法模式(Template Method Pattern)

应用场景:假设我们有一个数据处理应用程序,需要处理不同类型的数据(如CSV和XML)。模板方法模式可以帮助我们定义一个算法的骨架,并允许子类实现具体步骤。

// 抽象类
public abstract class DataProcessor
{
    // 模板方法
    public void ProcessData()
    {
        ReadData();
        Process();
        SaveData();
    }

    protected abstract void ReadData();
    protected abstract void Process();
    protected abstract void SaveData();
}

// 具体类
public class CSVDataProcessor : DataProcessor
{
    protected override void ReadData()
    {
        Console.WriteLine("Reading CSV Data");
    }

    protected override void Process()
    {
        Console.WriteLine("Processing CSV Data");
    }

    protected override void SaveData()
    {
        Console.WriteLine("Saving CSV Data");
    }
}

public class XMLDataProcessor : DataProcessor
{
    protected override void ReadData()
    {
        Console.WriteLine("Reading XML Data");
    }

    protected override void Process()
    {
        Console.WriteLine("Processing XML Data");
    }

    protected override void SaveData()
    {
        Console.WriteLine("Saving XML Data");
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        DataProcessor csvProcessor = new CSVDataProcessor();
        csvProcessor.ProcessData();

        DataProcessor xmlProcessor = new XMLDataProcessor();
        xmlProcessor.ProcessData();
    }
}

22. 状态模式(State Pattern)

应用场景:假设我们有一个订单处理系统,订单可以处于不同的状态(如新建、已支付、已发货、已完成)。状态模式可以帮助我们将状态相关的行为封装到不同的状态对象中。

// 状态接口
public interface IOrderState
{
    void Handle(OrderContext context);
}

// 具体状态类
public class NewOrderState : IOrderState
{
    public void Handle(OrderContext context)
    {
        Console.WriteLine("Order is in New State");
        context.SetState(new PaidOrderState());
    }
}

public class PaidOrderState : IOrderState
{
    public void Handle(OrderContext context)
    {
        Console.WriteLine("Order is in Paid State");
        context.SetState(new ShippedOrderState());
    }
}

public class ShippedOrderState : IOrderState
{
    public void Handle(OrderContext context)
    {
        Console.WriteLine("Order is in Shipped State");
        context.SetState(new CompletedOrderState());
    }
}

public class CompletedOrderState : IOrderState
{
    public void Handle(OrderContext context)
    {
        Console.WriteLine("Order is in Completed State");
    }
}

// 上下文类
public class OrderContext
{
    private IOrderState state;

    public OrderContext()
    {
        state = new NewOrderState();
    }

    public void SetState(IOrderState state)
    {
        this.state = state;
    }

    public void Request()
    {
        state.Handle(this);
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        OrderContext order = new OrderContext();
        order.Request();
        order.Request();
        order.Request();
        order.Request();
    }
}

23. 迭代器模式(Iterator Pattern)

应用场景:假设我们有一个图书馆系统,需要遍历不同类型的集合(如书籍集合、杂志集合)。迭代器模式可以帮助我们提供一种统一的方式来遍历这些集合。

// 迭代器接口
public interface IIterator
{
    bool HasNext();
    object Next();
}

// 聚合接口
public interface IAggregate
{
    IIterator CreateIterator();
}

// 具体聚合类
public class BookCollection : IAggregate
{
    private List<string> books = new List<string>();

    public void AddBook(string book)
    {
        books.Add(book);
    }

    public IIterator CreateIterator()
    {
        return new BookIterator(this);
    }

    public int Count
    {
        get { return books.Count; }
    }

    public string this[int index]
    {
        get { return books[index]; }
    }
}

// 具体迭代器类
public class BookIterator : IIterator
{
    private BookCollection collection;
    private int currentIndex = 0;

    public BookIterator(BookCollection collection)
    {
        this.collection = collection;
    }

    public bool HasNext()
    {
        return currentIndex < collection.Count;
    }

    public object Next()
    {
        return collection[currentIndex++];
    }
}

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        BookCollection books = new BookCollection();
        books.AddBook("Book 1");
        books.AddBook("Book 2");
        books.AddBook("Book 3");

        IIterator iterator = books.CreateIterator();
        while (iterator.HasNext())
        {
            string book = (string)iterator.Next();
            Console.WriteLine(book);
        }
    }
}
posted @   firespeed  阅读(198)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起