设计模式实战

1. 概述

1.1 设计模式的重要性

设计模式(Design Pattern)是面向对象软件设计中常见问题的解决方案,是代码设计经验的总结,能够提高代码的可维护性、可扩展性和可复用性。

本文内容

  • 创建型模式:单例、工厂、建造者、原型等模式
  • 结构型模式:适配器、装饰器、代理、外观等模式
  • 行为型模式:观察者、策略、责任链、模板方法等模式
  • 实战应用:设计模式在实际项目中的应用场景

1.2 本文内容结构

本文将从以下几个方面深入探讨设计模式实战:

  1. 创建型模式:对象创建的设计模式
  2. 结构型模式:类和对象组合的设计模式
  3. 行为型模式:对象间通信的设计模式
  4. 模式组合:多种设计模式的组合使用
  5. 实战案例:设计模式在实际项目中的应用

2. 创建型模式

2.1 单例模式

2.1.1 单例模式实现

单例模式(Singleton):确保一个类只有一个实例,并提供全局访问点。

单例模式实现

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
62
63
64
65
// 饿汉式单例
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();

private EagerSingleton() {}

public static EagerSingleton getInstance() {
return instance;
}
}

// 懒汉式单例(线程不安全)
public class LazySingleton {
private static LazySingleton instance;

private LazySingleton() {}

public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}

// 双重检查锁定单例
public class DoubleCheckSingleton {
private volatile static DoubleCheckSingleton instance;

private DoubleCheckSingleton() {}

public static DoubleCheckSingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckSingleton.class) {
if (instance == null) {
instance = new DoubleCheckSingleton();
}
}
}
return instance;
}
}

// 静态内部类单例(推荐)
public class StaticInnerClassSingleton {
private StaticInnerClassSingleton() {}

private static class SingletonHolder {
private static final StaticInnerClassSingleton instance =
new StaticInnerClassSingleton();
}

public static StaticInnerClassSingleton getInstance() {
return SingletonHolder.instance;
}
}

// 枚举单例(推荐,线程安全,防止反序列化)
public enum EnumSingleton {
INSTANCE;

public void doSomething() {
// 业务方法
}
}

2.2 工厂模式

2.2.1 简单工厂模式

简单工厂模式(Simple Factory):由一个工厂类根据传入的参数决定创建哪种产品类的实例。

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
// 产品接口
public interface Product {
void use();
}

// 具体产品A
public class ConcreteProductA implements Product {
@Override
public void use() {
System.out.println("Using Product A");
}
}

// 具体产品B
public class ConcreteProductB implements Product {
@Override
public void use() {
System.out.println("Using Product B");
}
}

// 简单工厂
public class SimpleFactory {
public static Product createProduct(String type) {
if ("A".equals(type)) {
return new ConcreteProductA();
} else if ("B".equals(type)) {
return new ConcreteProductB();
}
throw new IllegalArgumentException("Unknown product type");
}
}

2.2.2 工厂方法模式

工厂方法模式(Factory Method):定义一个创建对象的接口,让子类决定实例化哪一个类。

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
// 产品接口
public interface Product {
void use();
}

// 具体产品A
public class ConcreteProductA implements Product {
@Override
public void use() {
System.out.println("Using Product A");
}
}

// 具体产品B
public class ConcreteProductB implements Product {
@Override
public void use() {
System.out.println("Using Product B");
}
}

// 工厂接口
public interface Factory {
Product createProduct();
}

// 具体工厂A
public class ConcreteFactoryA implements Factory {
@Override
public Product createProduct() {
return new ConcreteProductA();
}
}

// 具体工厂B
public class ConcreteFactoryB implements Factory {
@Override
public Product createProduct() {
return new ConcreteProductB();
}
}

2.2.3 抽象工厂模式

抽象工厂模式(Abstract Factory):提供一个创建一系列相关或相互依赖对象的接口。

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
// 产品A接口
public interface ProductA {
void useA();
}

// 产品B接口
public interface ProductB {
void useB();
}

// 具体产品A1
public class ConcreteProductA1 implements ProductA {
@Override
public void useA() {
System.out.println("Using Product A1");
}
}

// 具体产品B1
public class ConcreteProductB1 implements ProductB {
@Override
public void useB() {
System.out.println("Using Product B1");
}
}

// 抽象工厂
public interface AbstractFactory {
ProductA createProductA();
ProductB createProductB();
}

// 具体工厂1
public class ConcreteFactory1 implements AbstractFactory {
@Override
public ProductA createProductA() {
return new ConcreteProductA1();
}

@Override
public ProductB createProductB() {
return new ConcreteProductB1();
}
}

2.3 建造者模式

2.3.1 建造者模式实现

建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

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
62
63
64
65
66
67
// 产品类
public class Product {
private String partA;
private String partB;
private String partC;

// Getters and setters
public String getPartA() { return partA; }
public void setPartA(String partA) { this.partA = partA; }
public String getPartB() { return partB; }
public void setPartB(String partB) { this.partB = partB; }
public String getPartC() { return partC; }
public void setPartC(String partC) { this.partC = partC; }
}

// 建造者接口
public interface Builder {
Builder buildPartA(String partA);
Builder buildPartB(String partB);
Builder buildPartC(String partC);
Product build();
}

// 具体建造者
public class ConcreteBuilder implements Builder {
private Product product = new Product();

@Override
public Builder buildPartA(String partA) {
product.setPartA(partA);
return this;
}

@Override
public Builder buildPartB(String partB) {
product.setPartB(partB);
return this;
}

@Override
public Builder buildPartC(String partC) {
product.setPartC(partC);
return this;
}

@Override
public Product build() {
return product;
}
}

// 指挥者
public class Director {
private Builder builder;

public Director(Builder builder) {
this.builder = builder;
}

public Product construct() {
return builder
.buildPartA("Part A")
.buildPartB("Part B")
.buildPartC("Part C")
.build();
}
}

2.4 原型模式

2.4.1 原型模式实现

原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

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
// 原型接口
public interface Prototype extends Cloneable {
Prototype clone();
}

// 具体原型
public class ConcretePrototype implements Prototype {
private String field;

public ConcretePrototype(String field) {
this.field = field;
}

@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone failed", e);
}
}

public String getField() { return field; }
public void setField(String field) { this.field = field; }
}

// 深拷贝实现
public class DeepPrototype implements Prototype {
private String field;
private ReferenceType reference;

public DeepPrototype(String field, ReferenceType reference) {
this.field = field;
this.reference = reference;
}

@Override
public Prototype clone() {
DeepPrototype clone = null;
try {
clone = (DeepPrototype) super.clone();
clone.reference = reference.clone(); // 深拷贝引用对象
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone failed", e);
}
return clone;
}
}

3. 结构型模式

3.1 适配器模式

3.1.1 适配器模式实现

适配器模式(Adapter):将一个类的接口转换成客户希望的另一个接口。

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
// 目标接口
public interface Target {
void request();
}

// 适配者类
public class Adaptee {
public void specificRequest() {
System.out.println("Adaptee specific request");
}
}

// 类适配器
public class ClassAdapter extends Adaptee implements Target {
@Override
public void request() {
specificRequest();
}
}

// 对象适配器
public class ObjectAdapter implements Target {
private Adaptee adaptee;

public ObjectAdapter(Adaptee adaptee) {
this.adaptee = adaptee;
}

@Override
public void request() {
adaptee.specificRequest();
}
}

3.2 装饰器模式

3.2.1 装饰器模式实现

装饰器模式(Decorator):动态地给一个对象添加一些额外的职责。

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
// 组件接口
public interface Component {
void operation();
}

// 具体组件
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("ConcreteComponent operation");
}
}

// 装饰器抽象类
public abstract class Decorator implements Component {
protected Component component;

public Decorator(Component component) {
this.component = component;
}

@Override
public void operation() {
component.operation();
}
}

// 具体装饰器A
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}

@Override
public void operation() {
super.operation();
addedBehavior();
}

private void addedBehavior() {
System.out.println("Added behavior A");
}
}

// 具体装饰器B
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}

@Override
public void operation() {
super.operation();
addedBehavior();
}

private void addedBehavior() {
System.out.println("Added behavior B");
}
}

3.3 代理模式

3.3.1 代理模式实现

代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问。

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
62
63
64
// 主题接口
public interface Subject {
void request();
}

// 真实主题
public class RealSubject implements Subject {
@Override
public void request() {
System.out.println("RealSubject request");
}
}

// 代理类
public class Proxy implements Subject {
private RealSubject realSubject;

@Override
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
preRequest();
realSubject.request();
postRequest();
}

private void preRequest() {
System.out.println("Pre request");
}

private void postRequest() {
System.out.println("Post request");
}
}

// 动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy implements InvocationHandler {
private Object target;

public DynamicProxy(Object target) {
this.target = target;
}

public Object getProxy() {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this
);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After method: " + method.getName());
return result;
}
}

3.4 外观模式

3.4.1 外观模式实现

外观模式(Facade):为子系统中的一组接口提供一个统一的接口。

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
// 子系统A
public class SubsystemA {
public void operationA() {
System.out.println("SubsystemA operation");
}
}

// 子系统B
public class SubsystemB {
public void operationB() {
System.out.println("SubsystemB operation");
}
}

// 子系统C
public class SubsystemC {
public void operationC() {
System.out.println("SubsystemC operation");
}
}

// 外观类
public class Facade {
private SubsystemA subsystemA;
private SubsystemB subsystemB;
private SubsystemC subsystemC;

public Facade() {
this.subsystemA = new SubsystemA();
this.subsystemB = new SubsystemB();
this.subsystemC = new SubsystemC();
}

public void operation() {
subsystemA.operationA();
subsystemB.operationB();
subsystemC.operationC();
}
}

4. 行为型模式

4.1 观察者模式

4.1.1 观察者模式实现

观察者模式(Observer):定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知。

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
import java.util.ArrayList;
import java.util.List;

// 观察者接口
public interface Observer {
void update(String message);
}

// 具体观察者A
public class ConcreteObserverA implements Observer {
@Override
public void update(String message) {
System.out.println("ObserverA received: " + message);
}
}

// 具体观察者B
public class ConcreteObserverB implements Observer {
@Override
public void update(String message) {
System.out.println("ObserverB received: " + message);
}
}

// 主题接口
public interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}

// 具体主题
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
private String state;

@Override
public void attach(Observer observer) {
observers.add(observer);
}

@Override
public void detach(Observer observer) {
observers.remove(observer);
}

@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(state);
}
}

public void setState(String state) {
this.state = state;
notifyObservers();
}
}

4.2 策略模式

4.2.1 策略模式实现

策略模式(Strategy):定义一系列算法,把它们封装起来,并且使它们可相互替换。

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
// 策略接口
public interface Strategy {
void execute();
}

// 具体策略A
public class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
System.out.println("Strategy A executed");
}
}

// 具体策略B
public class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
System.out.println("Strategy B executed");
}
}

// 上下文类
public class Context {
private Strategy strategy;

public Context(Strategy strategy) {
this.strategy = strategy;
}

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

public void executeStrategy() {
strategy.execute();
}
}

4.3 责任链模式

4.3.1 责任链模式实现

责任链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。

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
// 处理器接口
public abstract class Handler {
protected Handler nextHandler;

public void setNext(Handler handler) {
this.nextHandler = handler;
}

public abstract void handleRequest(Request request);
}

// 具体处理器A
public class ConcreteHandlerA extends Handler {
@Override
public void handleRequest(Request request) {
if (request.getType().equals("A")) {
System.out.println("HandlerA handled request");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}

// 具体处理器B
public class ConcreteHandlerB extends Handler {
@Override
public void handleRequest(Request request) {
if (request.getType().equals("B")) {
System.out.println("HandlerB handled request");
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}

// 请求类
public class Request {
private String type;

public Request(String type) {
this.type = type;
}

public String getType() { return type; }
}

4.4 模板方法模式

4.4.1 模板方法模式实现

模板方法模式(Template Method):定义一个操作中算法的骨架,而将一些步骤延迟到子类中。

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
// 抽象类
public abstract class AbstractClass {
// 模板方法
public final void templateMethod() {
step1();
step2();
step3();
}

// 具体步骤
protected void step1() {
System.out.println("Abstract step1");
}

// 抽象步骤,由子类实现
protected abstract void step2();

// 钩子方法
protected void step3() {
System.out.println("Abstract step3");
}
}

// 具体类A
public class ConcreteClassA extends AbstractClass {
@Override
protected void step2() {
System.out.println("ConcreteClassA step2");
}
}

// 具体类B
public class ConcreteClassB extends AbstractClass {
@Override
protected void step2() {
System.out.println("ConcreteClassB step2");
}

@Override
protected void step3() {
System.out.println("ConcreteClassB step3");
}
}

4.5 命令模式

4.5.1 命令模式实现

命令模式(Command):将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。

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
// 命令接口
public interface Command {
void execute();
void undo();
}

// 具体命令
public class ConcreteCommand implements Command {
private Receiver receiver;

public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}

@Override
public void execute() {
receiver.action();
}

@Override
public void undo() {
receiver.undoAction();
}
}

// 接收者
public class Receiver {
public void action() {
System.out.println("Receiver action");
}

public void undoAction() {
System.out.println("Receiver undo action");
}
}

// 调用者
public class Invoker {
private Command command;

public void setCommand(Command command) {
this.command = command;
}

public void executeCommand() {
command.execute();
}
}

5. 模式组合

5.1 模式组合使用

5.1.1 多种模式组合

模式组合示例

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
62
63
64
65
66
// 使用工厂模式创建对象
// 使用策略模式选择算法
// 使用观察者模式通知变化

// 工厂模式创建策略
public class StrategyFactory {
public static Strategy createStrategy(String type) {
switch (type) {
case "A":
return new ConcreteStrategyA();
case "B":
return new ConcreteStrategyB();
default:
throw new IllegalArgumentException("Unknown strategy type");
}
}
}

// 使用装饰器模式增强策略
public class StrategyDecorator implements Strategy {
private Strategy strategy;

public StrategyDecorator(Strategy strategy) {
this.strategy = strategy;
}

@Override
public void execute() {
System.out.println("Before strategy execution");
strategy.execute();
System.out.println("After strategy execution");
}
}

// 使用观察者模式监听策略执行
public class StrategyContext implements Subject {
private Strategy strategy;
private List<Observer> observers = new ArrayList<>();

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
notifyObservers();
}

public void executeStrategy() {
strategy.execute();
notifyObservers();
}

@Override
public void attach(Observer observer) {
observers.add(observer);
}

@Override
public void detach(Observer observer) {
observers.remove(observer);
}

@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update("Strategy changed");
}
}
}

6. 实战案例

6.1 订单系统设计

6.1.1 订单系统模式应用

订单系统设计模式应用

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
// 使用工厂模式创建订单
public class OrderFactory {
public static Order createOrder(String orderType) {
switch (orderType) {
case "NORMAL":
return new NormalOrder();
case "VIP":
return new VipOrder();
case "DISCOUNT":
return new DiscountOrder();
default:
throw new IllegalArgumentException("Unknown order type");
}
}
}

// 使用策略模式计算价格
public interface PriceStrategy {
BigDecimal calculate(BigDecimal price);
}

public class NormalPriceStrategy implements PriceStrategy {
@Override
public BigDecimal calculate(BigDecimal price) {
return price;
}
}

public class VipPriceStrategy implements PriceStrategy {
@Override
public BigDecimal calculate(BigDecimal price) {
return price.multiply(new BigDecimal("0.8"));
}
}

// 使用观察者模式通知订单状态变化
public class Order implements Subject {
private OrderStatus status;
private List<Observer> observers = new ArrayList<>();

public void setStatus(OrderStatus status) {
this.status = status;
notifyObservers();
}

@Override
public void attach(Observer observer) {
observers.add(observer);
}

@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update("Order status changed to: " + status);
}
}
}

6.2 缓存系统设计

6.2.1 缓存系统模式应用

缓存系统设计模式应用

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
// 使用单例模式管理缓存
public class CacheManager {
private static volatile CacheManager instance;
private Map<String, Object> cache = new ConcurrentHashMap<>();

private CacheManager() {}

public static CacheManager getInstance() {
if (instance == null) {
synchronized (CacheManager.class) {
if (instance == null) {
instance = new CacheManager();
}
}
}
return instance;
}

public void put(String key, Object value) {
cache.put(key, value);
}

public Object get(String key) {
return cache.get(key);
}
}

// 使用代理模式实现缓存代理
public class CacheProxy implements DataService {
private DataService realService;
private CacheManager cacheManager;

public CacheProxy(DataService realService) {
this.realService = realService;
this.cacheManager = CacheManager.getInstance();
}

@Override
public Object getData(String key) {
Object data = cacheManager.get(key);
if (data == null) {
data = realService.getData(key);
cacheManager.put(key, data);
}
return data;
}
}

7. 设计模式选择

7.1 模式选择原则

7.1.1 何时使用设计模式

设计模式选择原则

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
// 1. 单例模式:需要全局唯一实例
// - 配置管理器
// - 连接池
// - 日志管理器

// 2. 工厂模式:需要创建对象,但不想暴露创建逻辑
// - 数据库连接工厂
// - 消息队列工厂
// - 支付方式工厂

// 3. 建造者模式:需要创建复杂对象
// - SQL查询构建器
// - HTTP请求构建器
// - 配置对象构建器

// 4. 适配器模式:需要将不兼容的接口转换为兼容的接口
// - 第三方库适配
// - 遗留系统集成
// - 接口升级

// 5. 装饰器模式:需要动态添加功能
// - IO流装饰
// - 权限检查装饰
// - 日志记录装饰

// 6. 代理模式:需要控制对象访问
// - 远程代理
// - 虚拟代理
// - 保护代理

// 7. 观察者模式:需要一对多的依赖关系
// - 事件监听
// - 消息订阅
// - 状态变化通知

// 8. 策略模式:需要多种算法可替换
// - 排序算法
// - 支付方式
// - 折扣计算

8. 总结

8.1 核心要点

  1. 创建型模式:关注对象创建,降低对象创建复杂度
  2. 结构型模式:关注类和对象的组合,形成更大的结构
  3. 行为型模式:关注对象间的通信和职责分配
  4. 模式组合:多种模式可以组合使用
  5. 模式选择:根据实际场景选择合适的模式

8.2 关键理解

  1. 设计模式本质:解决常见设计问题的经验总结
  2. 模式不是银弹:不要过度使用设计模式
  3. 模式组合:实际项目中往往需要组合多种模式
  4. 模式演进:理解模式原理,灵活应用
  5. 代码可读性:使用模式提高代码可维护性

8.3 最佳实践

  1. 理解原理:深入理解设计模式的原理和适用场景
  2. 适度使用:不要为了使用模式而使用模式
  3. 模式组合:根据实际需求组合使用多种模式
  4. 代码重构:使用设计模式重构现有代码
  5. 持续学习:不断学习新的设计模式和最佳实践

相关文章