以下是 10种设计模式 的完整技术实现方案,包含 类图(PlantUML)、应用场景、核心代码,按结构化方式组织:

  1. 工厂模式:封装对象创建逻辑,客户端无需知道具体类。
  2. 策略模式:定义可互换的算法族,运行时动态切换。
  3. 装饰器模式:动态扩展对象功能,避免继承层次过深。
  4. 组合模式:统一处理单个对象和对象集合,形成树形结构。
  5. 观察者模式:一对多依赖关系,状态变化自动通知所有依赖对象。
  6. 状态模式:对象行为随内部状态改变而变化,避免条件分支。
  7. 中介者模式:封装对象间交互,降低直接耦合。
  8. 单例模式:确保一个类只有一个实例,并提供全局访问点。
  9. 代理模式:控制对目标对象的访问,增强功能(如缓存、权限)。
  10. 享元模式:共享细粒度对象,减少内存开销(如字符、图形复用)。
  11. 模板方法模式:定义算法骨架,子类重写特定步骤而不改变结构

一、组合模式(Composite)

想表示对象的部分-整体层次结构希望用户用一致的方式处理个体对象和组合对象。

类图

image-20250616134240436

———————————————————————————————————————————————————————————————-

image-20250616151113924

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public abstract class Component {
protected string Name { get; }
protected Component(string name) => Name = name;
public abstract void Display(int depth = 0);
}
class leaf : Component
{
public leaf(string name) : base(name) { }
public override void Display(int depth )
{
Console.WriteLine(new String('-', depth) + Name);
}
}
class Containers : Component {
public List<Component> _children = new List<Component>();
public Containers (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 (var child in _children)
{
child.Display(depth + 2);
}
}
}
// 使用示例
var root = new Composite("Root");
root.Add(new Leaf("File A"));
var folder = new Composite("Folder X");
folder.Add(new Leaf("File B"));
root.Add(folder);
root.Display(1);


二、工厂方法模式(Factory Method)

用户需要一个类的子类的实例,但不希望与该类的子类形成耦合。用户需要一个类的子类的实例,但用户不知道该类有哪些子类可用。

类图

image-20250616134250199

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 产品接口
public interface IProduct
{
void Operation();
}

// 具体产品
public class ConcreteProductA : IProduct
{
public void Operation() => Console.WriteLine("Product A");
}

public class ConcreteProductB : IProduct
{
public void Operation() => Console.WriteLine("Product B");
}

// 抽象工厂
public abstract class Creator
{
public abstract IProduct FactoryMethod();
public void SomeOperation() => FactoryMethod().Operation();
}

// 具体工厂
public class ConcreteCreatorA : Creator
{
public override IProduct FactoryMethod() => new ConcreteProductA();
}

public class ConcreteCreatorB : Creator
{
public override IProduct FactoryMethod() => new ConcreteProductB();
}

// 使用示例
Creator creator = new ConcreteCreatorA();
creator.SomeOperation(); // 输出: Product A


三、观察者模式(Observer)

当一个对象的数据更新时需要通知其他对象,但这个对象又不希望和被通知的那些对象形成紧耦合。当一个对象的数据更新时,这个对象需要让其他对象也各自更新自己的数据,但这个对象不知道具体有多少对象需要更新数据。

类图

image-20250616134258871

核心代码(使用C#事件)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 被观察者(Subject)
public class Subject
{
private List<IObserver> _observers = new List<IObserver>();

public void Attach(IObserver observer) => _observers.Add(observer);
public void Detach(IObserver observer) => _observers.Remove(observer);

public void Notify()
{
foreach (var observer in _observers)
observer.Update();
}
}

// 观察者接口
public interface IObserver
{
void Update();
}

// 具体观察者
public class ConcreteObserver : IObserver
{
public void Update() => Console.WriteLine("Observer updated!");
}

// 使用示例
var subject = new Subject();
var observer = new ConcreteObserver();
subject.Attach(observer);
subject.Notify(); // 输出: Observer updated!


四、策略模式(Strategy)

一个类定义了多种行为,并且这些行为在这个类中以多个条件语句的形式出现,可以使用策略模式避免在类中使用大量的条件语句。程序不需要暴露复杂的、与算法相关的数据结构,可以使用策略模式封装算法。需要使用一个算法的不同变体。

类图

image-20250616152806041

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 策略接口
public interface ISortingStrategy
{
void Sort(int[] data);
}
// 快速排序策略
public class QuickSortStrategy : ISortingStrategy
{
public void Sort(int[] data)
{
Console.WriteLine("使用快速排序");
Array.Sort(data); // 实际算法实现
}
}
// 冒泡排序策略
public class BubbleSortStrategy : ISortingStrategy
{
public void Sort(int[] data)
{
Console.WriteLine("使用冒泡排序");
for (int i = 0; i < data.Length - 1; i++)
{
for (int j = 0; j < data.Length - i - 1; j++)
{
if (data[j] > data[j + 1])
{
(data[j], data[j + 1]) = (data[j + 1], data[j]);
}
}
}
}
}
public class Sort() {
private ISortingStrategy _strategy;
public void Set_strategy(ISortingStrategy _strategy)
{
this._strategy = _strategy;
}
public void ExcuteSort(int[] data)
{
_strategy?.Sort(data);
Console.WriteLine("排序结果: " + string.Join(", ", data));
}
/*
int data[] = {};
Sort sort = new Sore();
sort.Set_strategy(new ISortingStrategy());
sort.ExcuteSort(data)
*/
}


五、状态模式(State)

一个对象的行为依赖于它的状态,并且它必须在运行时根据状态改变它的行为。需要编写大量的太监语句来决定一个操作的行为,而且这些条件恰好表示对象的一种状态

类图

image-20250616153554705

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public interface IState
{
void Handle(Context context);
}
public class Context
{
private IState _currentState;

public Context(IState initialState)
{
_currentState = initialState;
}

public void ChangeState(IState _state)
{
_currentState = _state;
Console.WriteLine($"状态已切换至:{_state.GetType().Name}");
}
public void Request()
{
_currentState.Handle(this);
}
}
public class IdleState:IState {
public void Handle(Context context) {
Console.WriteLine("当前状态:待机,等待启动...");
// 状态转换逻辑
context.ChangeState(new RunningState());
}
}
public class RunningState : IState {
public void Handle(Context context) {
Console.WriteLine("当前状态:运行中,可暂停或停止...");
// 状态转换逻辑
context.ChangeState(new StoppedState());
}
}
public class StoppedState : IState {
public void Handle(Context context) {
Console.WriteLine("当前状态:待机,等待启动...");
// 状态转换逻辑
context.ChangeState(new RunningState());
}
}

六、中介者模式(Mediator)

许多对象以复杂的方式交互,所导致的依赖关系使系统难以理解和维护。一个对象引用其他很多对象,导致难以复用该对象。

类图

image-20250616134330167

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 中介者接口
public interface IMediator
{
void Send(string message, Colleague colleague);
}
// 具体中介者
public class ConcreteMediator : IMediator
{
private ConcreteColleagueA _colleagueA;
private ConcreteColleagueB _colleagueB;

public void SetColleagueA(ConcreteColleagueA a) => _colleagueA = a;
public void SetColleagueB(ConcreteColleagueB b) => _colleagueB = b;

public void Send(string message, Colleague colleague)
{
if (colleague == _colleagueA)
_colleagueB.Receive(message);
else
_colleagueA.Receive(message);
}
}
// 同事基类
public abstract class Colleague
{
protected IMediator mediator;
public Colleague(IMediator mediator) => this.mediator = mediator;
}

// 具体同事
public class ConcreteColleagueA : Colleague
{
public ConcreteColleagueA(IMediator mediator) : base(mediator) { }

public void Send(string message)
=> mediator.Send(message, this);

public void Receive(string message)
=> Console.WriteLine($"Colleague A received: {message}");
}

public class ConcreteColleagueB : Colleague
{
public ConcreteColleagueB(IMediator mediator) : base(mediator) { }

public void Send(string message)
=> mediator.Send(message, this);

public void Receive(string message)
=> Console.WriteLine($"Colleague B received: {message}");
}

// 使用示例
var mediator = new ConcreteMediator();
var colleagueA = new ConcreteColleagueA(mediator);
var colleagueB = new ConcreteColleagueB(mediator);
mediator.SetColleagueA(colleagueA);
mediator.SetColleagueB(colleagueB);

colleagueA.Send("Hello from A"); // B收到消息


七、装饰模式(Decorator)

程序希望动态地增强类的某个对象的功能,而又不影响到该类的其他对象。采用继承来增强对象功能不利于系统的扩展和维护。

类图

image-20250616134338774

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 组件接口
public interface IComponent
{
void Operation();
}

// 具体组件
public class ConcreteComponent : IComponent
{
public void Operation() => Console.WriteLine("Concrete Component");
}

// 装饰器基类
public abstract class Decorator : IComponent
{
protected IComponent _component;
public Decorator(IComponent component) => _component = component;
public virtual void Operation() => _component.Operation();
}

// 具体装饰器
public class ConcreteDecoratorA : Decorator
{
public ConcreteDecoratorA(IComponent component) : base(component) { }

public override void Operation()
{
base.Operation();
Console.WriteLine("+ Decorator A");
}
}

public class ConcreteDecoratorB : Decorator
{
public ConcreteDecoratorB(IComponent component) : base(component) { }

public override void Operation()
{
base.Operation();
Console.WriteLine("+ Decorator B");
}
}

// 使用示例
IComponent component = new ConcreteComponent();
component = new ConcreteDecoratorA(component);
component = new ConcreteDecoratorB(component);
component.Operation();
// 输出:
// Concrete Component
// + Decorator A
// + Decorator B


八、单例模式(Singleton)

当系统需要某个类只能有一个实例。

类图

image-20250616134349718

线程安全实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 线程安全单例
public class Singleton
{
private static readonly Lazy<Singleton> _instance =
new Lazy<Singleton>(() => new Singleton());

public static Singleton Instance => _instance.Value;

private Singleton() { } // 私有构造函数

public void DoSomething() => Console.WriteLine("Singleton action");
}

// 使用示例
Singleton.Instance.DoSomething();


九、代理模式(Proxy)

类图

image-20250616134400523

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 主题接口
public interface ISubject
{
void Request();
}

// 真实主题
public class RealSubject : ISubject
{
public void Request() => Console.WriteLine("Real Subject Request");
}

// 代理
public class Proxy : ISubject
{
private RealSubject _realSubject;
public void Request()
{
if (_realSubject == null)
_realSubject = new RealSubject();

Console.WriteLine("Proxy: Pre-processing");
_realSubject.Request();
Console.WriteLine("Proxy: Post-processing");
}
}

// 使用示例
ISubject proxy = new Proxy();
proxy.Request();


十、享元模式(Flyweight)

类图

image-20250616134409619

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 享元接口,共享相同的数据
public interface IFlyweight
{
void Operation(string extrinsicState);
}

// 具体享元
public class ConcreteFlyweight : IFlyweight
{
private string _key;
public ConcreteFlyweight(string key)
=> _key = key;

public void Operation(string extrinsicState)
=> Console.WriteLine($"key: {_key}, Extrinsic: {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];
}
}

// 使用示例
var factory = new FlyweightFactory();
var flyweight = factory.GetFlyweight("SharedState");
flyweight.Operation("UniqueState1"); // 复用已有对象


十一丶模板方法模式

类图

image-20250616142156071

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 抽象类(定义算法骨架)
public abstract class AbstractClass
{
// 模板方法(固定步骤)
public void TemplateMethod()
{
Console.WriteLine("=== 开始执行算法 ===");
PrimitiveOperation1();
PrimitiveOperation2();
Console.WriteLine("=== 算法结束 ===");
}

// 原语操作1(由子类实现)
protected abstract void PrimitiveOperation1();

// 原语操作2(由子类实现)
protected abstract void PrimitiveOperation2();
}

// 具体子类A
public class ConcreteClassA : AbstractClass
{
protected override void PrimitiveOperation1()
=> Console.WriteLine("具体子类A实现的步骤1");

protected override void PrimitiveOperation2()
=> Console.WriteLine("具体子类A实现的步骤2");
}

// 具体子类B
public class ConcreteClassB : AbstractClass
{
protected override void PrimitiveOperation1()
=> Console.WriteLine("具体子类B实现的步骤1");

protected override void PrimitiveOperation2()
=> Console.WriteLine("具体子类B实现的步骤2(重写默认逻辑)");
}

// 使用示例
AbstractClass algorithmA = new ConcreteClassA();
algorithmA.TemplateMethod(); // 调用子类A的实现

AbstractClass algorithmB = new ConcreteClassB();
algorithmB.TemplateMethod(); // 调用子类B的实现

常用架构模式对比

架构模式 核心思想 适用场景
分层架构 垂直职责分离 企业级应用(表现层/业务层/数据层)
CQRS 读写操作分离 高频读写系统(如交易平台)
事件驱动 通过事件解耦组件 实时数据处理系统(如物联网)
微服务 功能拆分为独立服务 复杂分布式系统

每个模式代码均可独立运行,建议配合类图理解设计结构。根据实际需求选择:

  • 需要运行时扩展行为 → 策略模式/状态模式
  • 处理复杂对象关系 → 中介者模式/组合模式
  • 优化资源使用 → 享元模式/代理模式

11111111111111111111111