设计模式分类及应用(C#)

发布:2024-09-13 16:14 阅读:13 点赞:0

在本文中,我们将设计模式分为三种主要类型:创建型、结构型和行为型。理解这些分类将帮助您为特定问题选择最合适的模式,并有效地应用于您的软件设计中。

一. 创建型设计模式

创建型模式关注对象的创建过程。在我的经验中,随着项目的规模扩大,管理对象的创建可能变得棘手。确保在正确的时间创建正确的对象至关重要,这些模式帮助我避免了许多麻烦。

1.1 创建型设计模式的类型

工厂方法模式 (Factory Method)

public abstract class Creator
{
    public abstract Product FactoryMethod();
}
public class ConcreteCreator : Creator
{
    public override Product FactoryMethod()
    {
        // 返回具体的产品对象
        return new ConcreteProduct();
    }
}

抽象工厂模式 (Abstract Factory)

public interface IAbstractFactory
{
    IProductA CreateProductA();
    IProductB CreateProductB();
}
public class ConcreteFactory : IAbstractFactory
{
    public IProductA CreateProductA()
    {
        return new ConcreteProductA();
    }

    public IProductB CreateProductB()
    {
        return new ConcreteProductB();
    }
}

单例模式 (Singleton)

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

    private Singleton() { }

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

建造者模式 (Builder)

public class Product
{
    public string PartA { getset; }
    public string PartB { getset; }
}
public class Builder
{
    private Product _product = new Product();

    public void BuildPartA()
    {
        _product.PartA = "PartA";
    }

    public void BuildPartB()
    {
        _product.PartB = "PartB";
    }

    public Product GetResult()
    {
        return _product;
    }
}

原型模式 (Prototype)

public abstract class Prototype
{
    public abstract Prototype Clone();
}
public class ConcretePrototype : Prototype
{
    public override Prototype Clone()
    {
        return (Prototype)this.MemberwiseClone();
    }
}

面临的挑战

我曾经在一个项目中遇到过对象创建逻辑分散在代码库各处的情况,这使得管理和扩展变得几乎不可能。通过应用工厂方法模式,我能够集中和简化创建过程,显著提高了项目的可维护性。

二. 结构型设计模式

结构型模式处理类和对象的组合。这些模式帮助我创建灵活和高效的系统,提供了明确的组装对象和类的指南。

2.1 结构型设计模式的类型

适配器模式 (Adapter)

public interface ITarget
{
    void Request();
}
public class Adapter : ITarget
{
    private readonly Adaptee _adaptee;

    public Adapter(Adaptee adaptee)
    {
        _adaptee = adaptee;
    }

    public void Request()
    {
        _adaptee.SpecificRequest();
    }
}

桥接模式 (Bridge)

public abstract class Abstraction
{
    protected IImplementor _implementor;

    public Abstraction(IImplementor implementor)
    {
        _implementor = implementor;
    }

    public abstract void Operation();
}
public class RefinedAbstraction : Abstraction
{
    public RefinedAbstraction(IImplementor implementor) : base(implementor) { }

    public override void Operation()
    {
        _implementor.OperationImpl();
    }
}

组合模式 (Composite)

public abstract class Component
{
    public abstract void Operation();
}
public class Composite : Component
{
    private readonly List _children = new List();

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

    public override void Operation()
    {
        foreach (var child in _children)
        {
            child.Operation();
        }
    }
}

装饰器模式 (Decorator)

public abstract class Component
{
    public abstract void Operation();
}
public class ConcreteDecorator : Component
{
    private readonly Component _component;

    public ConcreteDecorator(Component component)
    {
        _component = component;
    }

    public override void Operation()
    {
        _component.Operation();
        // 添加额外的行为
    }
}

外观模式 (Facade)

public class Facade
{
    private readonly SubsystemA _subsystemA = new SubsystemA();
    private readonly SubsystemB _subsystemB = new SubsystemB();

    public void Operation()
    {
        _subsystemA.OperationA();
        _subsystemB.OperationB();
    }
}

享元模式 (Flyweight)

public interface IFlyweight
{
    void Operation();
}
public class ConcreteFlyweight : IFlyweight
{
    public void Operation()
    {
        // 执行操作
    }
}

代理模式 (Proxy)

public interface ISubject
{
    void Request();
}
public class Proxy : ISubject
{
    private readonly RealSubject _realSubject = new RealSubject();

    public void Request()
    {
        // 执行代理逻辑
        _realSubject.Request();
    }
}

面临的挑战

在将新功能集成到现有系统中时,往往感觉像在走钢丝——一步走错,一切可能崩溃。适配器模式特别有用,允许我使新组件与旧系统无缝工作,而无需大规模重构。

三. 行为型设计模式

行为型模式关注对象之间的交互和通信。这些模式对于管理复杂的工作流以及确保应用程序的不同部分和谐地工作至关重要。

3.1 行为型设计模式的类型

职责链模式 (Chain of Responsibility)

public abstract class Handler
{
    protected Handler _successor;

    public void SetSuccessor(Handler successor)
    {
        _successor = successor;
    }

    public abstract void HandleRequest();
}
public class ConcreteHandler : Handler
{
    public override void HandleRequest()
    {
        // 处理请求,或将其传递给下一个处理者
    }
}

命令模式 (Command)

public interface ICommand
{
    void Execute();
}
public class ConcreteCommand : ICommand
{
    public void Execute()
    {
        // 执行具体命令
    }
}

解释器模式 (Interpreter)

public interface Expression
{
    int Interpret();
}
public class TerminalExpression : Expression
{
    private readonly int _value;

    public TerminalExpression(int value)
    {
        _value = value;
    }

    public int Interpret()
    {
        return _value;
    }
}

迭代器模式 (Iterator)

public interface Iterator
{
    bool HasNext();
    object Next();
}
public class ConcreteIterator : Iterator
{
    public bool HasNext()
    {
        // 检查是否还有下一个元素
    }

    public object Next()
    {
        // 返回下一个元素
    }
}

中介者模式 (Mediator)

public interface IMediator
{
    void Notify(object sender, string eventType);
}
public class ConcreteMediator : IMediator
{
    public void Notify(object sender, string eventType)
    {
        // 根据事件类型通知相关对象
    }
}

备忘录模式 (Memento)

public class Memento
{
    public string State { getset; }
}
public class Originator
{
    private string _state;

    public Memento CreateMemento()
    {
        return new Memento { State = _state };
    }

    public void SetMemento(Memento memento)
    {
        _state = memento.State;
    }
}

观察者模式 (Observer)

public interface IObserver
{
    void Update();
}
public class ConcreteObserver : IObserver
{
    public void Update()
    {
        // 响应更新
    }
}

状态模式 (State)

public interface IState
{
    void Handle();
}
public class ConcreteState : IState
{
   



 public void Handle()
    {
        // 处理状态逻辑
    }
}

策略模式 (Strategy)

public interface IStrategy
{
    void Execute();
}
public class ConcreteStrategy : IStrategy
{
    public void Execute()
    {
        // 执行策略
    }
}

模板方法模式 (Template Method)

public abstract class AbstractClass
{
    public void TemplateMethod()
    {
        PrimitiveOperation1();
        PrimitiveOperation2();
    }

    protected abstract void PrimitiveOperation1();
    protected abstract void PrimitiveOperation2();
}
public class ConcreteClass : AbstractClass
{
    protected override void PrimitiveOperation1()
    {
        // 实现操作1
    }

    protected override void PrimitiveOperation2()
    {
        // 实现操作2
    }
}

访问者模式 (Visitor)

public interface IVisitor
{
    void Visit(ConcreteElement element);
}
public class ConcreteVisitor : IVisitor
{
    public void Visit(ConcreteElement element)
    {
        // 访问元素
    }
}

面临的挑战

在一个项目中,我需要处理动态用户行为,这些行为频繁根据各种输入变化。实现策略模式允许我轻松切换不同的行为,使应用程序更加稳健,能够适应变化。

实际案例和示例

为了说明这些模式,考虑智能家居系统的示例:

创建型模式

管理不同类型的智能设备(如灯光、恒温器)及其配置。

结构型模式

将各种设备集成到统一的控制界面中,并动态提供额外功能。

行为型模式

定义不同设备之间的交互(例如,灯光和恒温器)并处理事件(例如,温度变化)。

四. 总结

设计模式可以分为三种主要类型:创建型、结构型和行为型。每种类型解决了软件设计的不同方面,有助于创建灵活、可维护和可扩展的系统。通过理解和应用这些模式,开发人员可以更有效地解决常见的设计问题,并改善应用程序的整体架构。