十三、设计模式
一共有 23 种常见的设计模式,它们分为三类:创建型、结构型和行为型。以下是这些设计模式的代码示例以及使用场景。

创建型设计模式 (Creational Patterns):
- 单例模式 (Singleton Pattern):
- 使用场景:当需要确保一个类只有一个实例,并提供一个全局访问点时,如日志记录器、数据库连接池等。
public class Singleton
{
private static Singleton instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
- 工厂方法模式 (Factory Method Pattern):
- 使用场景:当需要根据特定条件创建不同类型的对象,如UI组件的创建、日志记录器的选择等。
public abstract class Product
{
public abstract void Create();
}
public class ConcreteProductA : Product
{
public override void Create()
{
Console.WriteLine("Product A is created. --from jhrs.com ");
}
}
public class ConcreteProductB : Product
{
public override void Create()
{
Console.WriteLine("Product B is created.--from jhrs.com ");
}
}
public abstract class Creator
{
public abstract Product FactoryMethod();
}
public class ConcreteCreatorA : Creator
{
public override Product FactoryMethod()
{
return new ConcreteProductA();
}
}
- 抽象工厂模式 (Abstract Factory Pattern):
- 使用场景:当需要一次性创建一组相关的对象,如创建操作系统相关的UI组件、数据库访问的抽象等。
public interface IProductA
{
void Create();
}
public interface IProductB
{
void Create();
}
public class ConcreteProductA1 : IProductA
{
public void Create()
{
Console.WriteLine("Product A1 is created.");
}
}
public class ConcreteProductA2 : IProductA
{
public void Create()
{
Console.WriteLine("Product A2 is created.");
}
}
public class ConcreteProductB1 : IProductB
{
public void Create()
{
Console.WriteLine("Product B1 is created.");
}
}
public class ConcreteProductB2 : IProductB
{
public void Create()
{
Console.WriteLine("Product B2 is created.");
}
}
public interface IAbstractFactory
{
IProductA CreateProductA();
IProductB CreateProductB();
}
public class ConcreteFactory1 : IAbstractFactory
{
public IProductA CreateProductA()
{
return new ConcreteProductA1();
}
public IProductB CreateProductB()
{
return new ConcreteProductB1();
}
}
- 建造者模式 (Builder Pattern):
- 使用场景:当需要构建一个复杂对象,且需要分步骤来构建不同部分时,如创建文档、报告等。
public class Product
{
public string PartA { get; set; }
public string PartB { get; set; }
}
public abstract class Builder
{
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
public class ConcreteBuilder : Builder
{
private Product product = new Product();
public override void BuildPartA()
{
product.PartA = "Part A--from jhrs.com ";
}
public override void BuildPartB()
{
product.PartB = "Part B--from jhrs.com ";
}
public override Product GetResult()
{
return product;
}
}
public class Director
{
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
}
}
- 原型模式 (Prototype Pattern):
- 使用场景:当需要复制对象而不暴露其具体构造细节时,如创建游戏中的角色、克隆对象等。
public interface ICloneable
{
ICloneable Clone();
}
public class ConcretePrototype : ICloneable
{
public int Number { get; set; }
public ICloneable Clone()
{
return new ConcretePrototype { Number = this.Number };
}
}
结构型设计模式 (Structural Patterns):
- 适配器模式 (Adapter Pattern):
- 使用场景:当需要将一个类的接口转换为另一个接口以满足客户端的期望接口时,如在新的库中使用旧的类。
public class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("Adaptee's specific request.--from jhrs.com ");
}
}
public interface ITarget
{
void Request();
}
public class Adapter : ITarget
{
private Adaptee adaptee = new Adaptee();
public void Request()
{
adaptee.SpecificRequest();
}
}
- 桥接模式 (Bridge Pattern):
- 使用场景:当需要将抽象部分与实现部分分离,以便它们可以独立地变化时,如不同操作系统上的图形用户界面。
public interface IImplementor
{
void OperationImpl();
}
public abstract class Abstraction
{
protected IImplementor implementor;
public Abstraction(IImplementor implementor)
{
this.implementor = implementor;
}
public abstract void Operation();
}
public class ConcreteImplementorA : IImplementor
{
public void OperationImpl()
{
Console.WriteLine("Concrete Implementor A operation.--from jhrs.com ");
}
}
public class ConcreteImplementorB : IImplementor
{
public void OperationImpl()
{
Console.WriteLine("Concrete Implementor B operation.");
}
}
public class RefinedAbstraction : Abstraction
{
public RefinedAbstraction(IImplementor implementor) : base(implementor) { }
public override void Operation()
{
implementor.OperationImpl();
}
}
- 组合模式 (Composite Pattern):
- 使用场景:当需要将对象组织成树形结构以表示部分-整体层次关系,并希望客户端统一处理单个对象和组合对象时,如图形用户界面中的控件树。
public abstract class Component
{
public string Name { get; set; }
public Component(string name)
{
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 override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + Name);
foreach (var child in children)
{
child.Display(depth + 2);
}
}
}
- 装饰器模式 (Decorator Pattern):
- 使用场景:当需要动态地为对象添加额外的职责时,而不影响其他对象时,如窗口系统中的窗口装饰。
public abstract class Component
{
public abstract void Operation();
}
public class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("Concrete Component operation.--from jhrs.com ");
}
}
public abstract class Decorator : Component
{
protected Component component;
public Decorator(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
public class ConcreteDecoratorA : Decorator
{
public ConcreteDecoratorA(Component component) : base(component) { }
public override void Operation()
{
base.Operation();
Console.WriteLine("Concrete Decorator A operation.");
}
}
public class ConcreteDecoratorB : Decorator
{
public ConcreteDecoratorB(Component component) : base(component) { }
public override void Operation()
{
base.Operation();
Console.WriteLine("Concrete Decorator B operation.--from jhrs.com ");
}
}
- 外观模式 (Facade Pattern):
- 使用场景:当需要提供一个简化的接口,隐藏复杂的子系统,以便客户端可以更轻松地与子系统交互时,如操作系统中的启动和关机功能。
public class SubsystemA
{
public void OperationA()
{
Console.WriteLine("Subsystem A operation.--from jhrs.com ");
}
}
public class SubsystemB
{
public void OperationB()
{
Console.WriteLine("Subsystem B operation.--from jhrs.com ");
}
}
public class Facade
{
private SubsystemA subsystemA;
private SubsystemB subsystemB;
public Facade()
{
subsystemA = new SubsystemA();
subsystemB = new SubsystemB();
}
public void Operation()
{
subsystemA.OperationA();
subsystemB.OperationB();
}
}
最新高级C#面试知识点
- 享元模式 (Flyweight Pattern):
- 使用场景:当需要共享大量细粒度的对象,以节省内存和提高性能时,如文本编辑器中的字符缓存。
public interface IFlyweight
{
void Operation(string extrinsicState);
}
public class ConcreteFlyweight : IFlyweight
{
public string IntrinsicState { get; private set; }
public ConcreteFlyweight(string intrinsicState)
{
IntrinsicState = intrinsicState;
}
public void Operation(string extrinsicState)
{
Console.WriteLine($"Flyweight with Intrinsic State '{IntrinsicState}' and Extrinsic State '{extrinsicState}'--from jhrs.com ");
}
}
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];
}
}
最新高级C#面试知识点
行为型设计模式 (Behavioral Patterns):
- 策略模式 (Strategy Pattern):
- 使用场景:当需要在运行时选择不同算法或行为时,如排序算法、支付方式的选择。
public interface IStrategy
{
void Execute();
}
public class ConcreteStrategyA : IStrategy
{
public void Execute()
{
Console.WriteLine("Strategy A is executed.--from jhrs.com ");
}
}
public class ConcreteStrategyB : IStrategy
{
public void Execute()
{
Console.WriteLine("Strategy B is executed.--from jhrs.com ");
}
}
public class Context
{
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void SetStrategy(IStrategy strategy)
{
this.strategy = strategy;
}
public void ExecuteStrategy()
{
strategy.Execute();
}
}
- 状态模式 (State Pattern):
- 使用场景:当对象的行为取决于其内部状态,并且需要在状态转换时改变其行为时,如自动售货机中的不同销售状态。
public interface IState
{
void Handle();
}
public class ConcreteStateA : IState
{
public void Handle()
{
Console.WriteLine("State A is handling.--from jhrs.com ");
}
}
public class ConcreteStateB : IState
{
public void Handle()
{
Console.WriteLine("State B is handling.--from jhrs.com ");
}
}
public class Context
{
private IState state;
public Context()
{
state = new ConcreteStateA();
}
public void ChangeState(IState newState)
{
state = newState;
}
public void Request()
{
state.Handle();
}
}
- 观察者模式 (Observer Pattern):
- 使用场景:当一个对象(主题)状态的改变需要通知其他对象(观察者)并保持松耦合时,如事件处理、消息传递系统。
public interface IObserver
{
void Update(string message);
}
public class ConcreteObserver : IObserver
{
private string name;
public ConcreteObserver(string name)
{
this.name = name;
}
public void Update(string message)
{
Console.WriteLine($"{name} received message: {message}--from jhrs.com ");
}
}
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);
}
}
}
- 备忘录模式 (Memento Pattern):
- 使用场景:当需要捕获和恢复对象的内部状态时,如文本编辑器中的撤销和重做功能。
public class Memento
{
public string State { get; }
public Memento(string state)
{
State = state;
}
}
public class Originator
{
public string State { get; set; }
public Memento CreateMemento()
{
return new
Memento(State);
}
public void RestoreMemento(Memento memento)
{
State = memento.State;
}
}
public class Caretaker
{
public Memento Memento { get; set; }
}
- 命令模式 (Command Pattern):
- 使用场景:当需要将请求封装成对象,以便可以在不同时间执行和排队请求,如遥控器中的按钮操作。
public interface ICommand
{
void Execute();
}
public class Receiver
{
public void Action()
{
Console.WriteLine("Receiver is performing an action.--from jhrs.com ");
}
}
public class ConcreteCommand : ICommand
{
private Receiver receiver;
public ConcreteCommand(Receiver receiver)
{
this.receiver = receiver;
}
public void Execute()
{
receiver.Action();
}
}
public class Invoker
{
private ICommand command;
public void SetCommand(ICommand command)
{
this.command = command;
}
public void ExecuteCommand()
{
command.Execute();
}
}
- 中介者模式 (Mediator Pattern):
- 使用场景:当多个对象之间需要相互通信,但不想让对象之间相互耦合时,如聊天室中的用户通信。
public interface IMediator
{
void Send(string message, Colleague colleague);
}
public class ConcreteMediator : IMediator
{
private Colleague colleague1;
private Colleague colleague2;
public void SetColleague1(Colleague colleague)
{
colleague1 = colleague;
}
public void SetColleague2(Colleague colleague)
{
colleague2 = colleague;
}
public void Send(string message, Colleague colleague)
{
if (colleague == colleague1)
{
colleague2.Receive(message);
}
else
{
colleague1.Receive(message);
}
}
}
public abstract class Colleague
{
protected IMediator mediator;
public Colleague(IMediator mediator)
{
this.mediator = mediator;
}
public abstract void Send(string message);
public abstract void Receive(string message);
}
- 访问者模式 (Visitor Pattern):
- 使用场景:当需要在不修改对象结构的情况下添加新操作时,如编译器中的抽象语法树遍历。
public interface IElement
{
void Accept(IVisitor visitor);
}
public class ConcreteElementA : IElement
{
public void Accept(IVisitor visitor)
{
visitor.VisitConcreteElementA(this);
}
}
public class ConcreteElementB : IElement
{
public void Accept(IVisitor visitor)
{
visitor.VisitConcreteElementB(this);
}
}
public interface IVisitor
{
void VisitConcreteElementA(ConcreteElementA element);
void VisitConcreteElementB(ConcreteElementB element);
}
public class ConcreteVisitor : IVisitor
{
public void VisitConcreteElementA(ConcreteElementA element)
{
Console.WriteLine("Visitor is processing ConcreteElementA.--from jhrs.com ");
}
public void VisitConcreteElementB(ConcreteElementB element)
{
Console.WriteLine("Visitor is processing ConcreteElementB.--from jhrs.com ");
}
}
最新高级C#面试知识点
- 解释器模式 (Interpreter Pattern):
- 使用场景:当需要定义语言的语法解析,并且可以解释和执行语言的表达式时,如编译器和解释器。
public abstract class AbstractExpression
{
public abstract void Interpret(Context context);
}
public class TerminalExpression : AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("Terminal expression is interpreted.--from jhrs.com ");
}
}
public class NonTerminalExpression : AbstractExpression
{
public override void Interpret(Context context)
{
Console.WriteLine("Non-terminal expression is interpreted.--from jhrs.com ");
}
}
public class Context
{
public string Input { get; set; }
}
最新高级C#面试知识点
- 迭代器模式 (Iterator Pattern):
- 使用场景:当需要提供一种顺序访问聚合对象中的元素的方法,而又不暴露其内部表示时,如集合类中的迭代器。
public interface IIterator
{
bool HasNext();
object Next();
}
public interface IAggregate
{
IIterator CreateIterator();
}
public class ConcreteIterator : IIterator
{
private List<object> items;
private int position = 0;
public ConcreteIterator(List<object> items)
{
this.items = items;
}
public bool HasNext()
{
return position < items.Count;
}
public object Next()
{
return items[position++];
}
}
public class ConcreteAggregate : IAggregate
{
private List<object> items = new List<object>();
public IIterator CreateIterator()
{
return new ConcreteIterator(items);
}
public void AddItem(object item)
{
items.Add(item);
}
}
最新高级C#面试知识点
- 责任链模式 (Chain of Responsibility Pattern):
- 使用场景:当多个对象处理同一请求,但具体处理者在运行时可动态确定时,如日志记录器链中的消息传递。
public abstract class Handler
{
protected Handler successor;
public void SetSuccessor(Handler successor)
{
this.successor = successor;
}
public abstract void HandleRequest(int request);
}
public class ConcreteHandlerA : Handler
{
public override void HandleRequest(int request)
{
if (request < 10)
{
Console.WriteLine($"Request {request} is handled by Handler A.--from jhrs.com ");
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}
public class ConcreteHandlerB : Handler
{
public override void HandleRequest(int request)
{
if (request >= 10 && request < 20)
{
Console.WriteLine($"Request {request} is handled by Handler B.--from jhrs.com ");
}
else if (successor != null)
{
successor.HandleRequest(request);
}
}
}
最新高级C#面试知识点
- 命令模式 (Command Pattern):
- 使用场景:当需要将请求封装成对象,以便可以在不同时间执行和排队请求,如遥控器中的按钮操作。
public interface ICommand
{
void Execute();
}
public class Receiver
{
public void Action()
{
Console.WriteLine("Receiver is performing an action.");
}
}
public class ConcreteCommand : ICommand
{
private Receiver receiver;
public ConcreteCommand(Receiver receiver)
{
this.receiver = receiver;
}
public void Execute()
{
receiver.Action();
}
}
public class Invoker
{
private ICommand command;
public void SetCommand(ICommand command)
{
this.command = command;
}
public void ExecuteCommand()
{
command.Execute();
}
}
最新高级C#面试知识点
- 策略模式 (Strategy Pattern):
- 使用场景:当需要在运行时选择不同算法或行为时,如排序算法、支付方式的选择。
public interface IStrategy
{
void Execute();
}
public class ConcreteStrategyA : IStrategy
{
public void Execute()
{
Console.WriteLine("Strategy A is executed.--from jhrs.com ");
}
}
public class ConcreteStrategyB : IStrategy
{
public void Execute()
{
Console.WriteLine("Strategy B is executed.--from jhrs.com ");
}
}
public class Context
{
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void SetStrategy(IStrategy strategy)
{
this.strategy = strategy;
}
public void ExecuteStrategy()
{
strategy.Execute();
}
}
最新高级C#面试知识点
这些是23种常见的设计模式的示例及其使用场景。根据具体的问题和需求,选择适当的设计模式以提高代码的可维护性、可扩展性和可理解性。

【江湖人士】(jhrs.com)原创文章,作者:江小编,如若转载,请注明出处:https://jhrs.com/2023/47094.html
扫码加入电报群,让你获得国外网赚一手信息。
文章标题:15+最新高级C#面试知识点