软考中级软件设计师——设计模式篇
一、设计模式核心分类
设计模式分为 3 大类,共 23 种模式(考试常考约 10-15 种):
分类 | 核心模式 | 考试重点 |
---|---|---|
创建型模式 | 工厂方法、抽象工厂、单例、生成器、原型 | 单例模式的实现(懒汉、饿汉)、工厂模式的应用场景 |
结构型模式 | 适配器、代理、装饰器、组合、外观、桥接 | 适配器与代理的区别、装饰器模式的动态扩展特性 |
行为型模式 | 观察者、策略、模板方法、职责链、状态、迭代器、备忘录、中介者、解释器 | 观察者模式的事件驱动、策略模式的算法替换、模板方法的流程固定步骤可扩展特性 |
二、设计模式分类(GoF 23种模式)
考试重点通常集中在以下分类及典型模式:
1. 创建型模式
核心:对象实例化的灵活控制。
1. 工厂方法模式(Factory Method)
-
定义:
定义一个创建对象的接口,但由子类决定具体实例化的类。 -
类图结构:
-
抽象工厂类(Creator):声明工厂方法(如
createProduct()
)。 -
具体工厂类(ConcreteCreator):实现工厂方法,返回具体产品对象。
-
抽象产品类(Product):定义产品的接口。
-
具体产品类(ConcreteProduct):实现产品接口。
-
-
应用场景:
-
日志记录器(不同格式的日志:文件、数据库)。
-
数据库连接(不同数据库驱动:MySQL、Oracle)。
-
-
优点:
-
符合开闭原则,新增产品只需扩展子类。
-
客户端代码与具体产品解耦。
-
-
代码示例(Java):
interface Product { void use(); } class ConcreteProductA implements Product { public void use() { /*...*/ } } abstract class Creator {public void operation() {Product p = createProduct();p.use();}abstract Product createProduct(); } class ConcreteCreatorA extends Creator {public Product createProduct() { return new ConcreteProductA(); } }
2. 抽象工厂模式(Abstract Factory)
-
定义:
提供一个接口,用于创建相关或依赖对象的家族,而无需指定具体类。 -
类图结构:
-
抽象工厂接口(AbstractFactory):声明一组创建产品的方法(如
createButton()
,createTextBox()
)。 -
具体工厂类(ConcreteFactory):实现接口,生成同一产品族的具体对象。
-
抽象产品接口(Button, TextBox):定义产品的功能。
-
具体产品类(WindowsButton, MacButton):实现不同平台的组件。
-
-
与工厂方法的区别:
-
工厂方法:针对单一产品等级结构。
-
抽象工厂:针对多个产品等级结构(产品族)。
-
-
缺点:
-
扩展新产品族困难(需修改抽象工厂接口)。
-
3. 单例模式(Singleton)
-
定义:
保证一个类只有一个实例,并提供它的全局访问点。 -
实现要点:
-
私有构造函数。
-
静态成员变量保存唯一实例。
-
提供静态方法获取实例(如
getInstance()
)。
-
-
线程安全实现:
-
双重检查锁(DCL)(适用于Java/C#):
public class Singleton {private static volatile Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;} }
-
静态内部类(延迟加载且线程安全):
public class Singleton {private Singleton() {}private static class Holder {static final Singleton INSTANCE = new Singleton();}public static Singleton getInstance() {return Holder.INSTANCE;} }
-
4. 生成器模式(Builder)
-
定义:
将一个复杂对象的构造过程与表示分离,使得同样的构建过程可以创建不同的表示。 -
类图结构:
-
抽象建造者(Builder):定义构建步骤的抽象接口(如
buildPartA()
,buildPartB()
)。 -
具体建造者(ConcreteBuilder):实现构建步骤,提供获取结果的接口。
-
指挥者(Director):构造一个使用Builder接口的对象。
-
产品(Product):最终构建的复杂对象。
-
-
应用场景:
-
生成复杂对象(如XML文档、HTML报表)。
-
创建具有多个可选参数的对象(避免构造函数参数爆炸)。
-
-
代码示例(简化版):
class Computer {private String cpu;private String ram;// 构造函数私有,只能通过Builder创建private Computer(Builder builder) { /*...*/ }static class Builder {private String cpu;private String ram;public Builder setCpu(String cpu) { this.cpu = cpu; return this; }public Builder setRam(String ram) { this.ram = ram; return this; }public Computer build() { return new Computer(this); }} } // 使用方式 Computer computer = new Computer.Builder().setCpu("i7").setRam("16GB").build();
5. 原型模式(Prototype)
-
定义:
用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象。 -
实现要点:
-
实现
Cloneable
接口(Java)或深拷贝逻辑。 -
提供
clone()
方法(浅拷贝需谨慎处理引用类型)。
-
-
应用场景:
-
对象创建成本较高(如数据库查询结果缓存后复制)。
-
需要动态配置对象属性(如游戏中的敌人克隆)。
-
-
深拷贝 vs 浅拷贝:
-
浅拷贝:复制基本类型字段,引用类型字段共享同一对象。
-
深拷贝:引用类型字段也递归复制。
-
-
代码示例(Java):
class Prototype implements Cloneable {private List<String> list = new ArrayList<>();@Overridepublic Prototype clone() {try {Prototype copy = (Prototype) super.clone();copy.list = new ArrayList<>(this.list); // 深拷贝listreturn copy;} catch (CloneNotSupportedException e) {return null;}} }
2. 结构型模式
核心:通过组合类或对象形成更大结构。
1. 适配器模式(Adapter)
-
定义:将一个类的接口转换成客户希望的另一个接口。
-
实现方式:
-
类适配器:通过继承适配者类实现目标接口。
-
对象适配器:通过组合适配者对象实现目标接口。
-
-
应用场景:
-
整合第三方库(如不同格式的日志接口转换)。
-
旧系统接口升级兼容。
-
-
代码示例:
// 目标接口 interface Target { void request(); }// 适配者类 class Adaptee { void specificRequest() { /*...*/ } }// 对象适配器 class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) { this.adaptee = adaptee; }public void request() { adaptee.specificRequest(); } }
2. 装饰器模式(Decorator)
-
定义:动态地为对象添加额外职责,避免子类膨胀。
-
结构:
-
组件接口(Component):定义一个对象接口,可以对这些对象动态地添加职责。
-
具体组件(ConcreteComponent):定义一个对象,可以对这个对象添加一些职责。
-
装饰器基类(Decorator):继承组件接口,持有组件实例。
-
具体装饰器(ConcreteDecorator):添加附加功能。
-
-
应用场景:
-
Java I/O流(如
BufferedInputStream
装饰FileInputStream
)。 -
动态扩展对象行为(如为订单添加折扣、税费计算)。
-
-
代码示例:
interface Coffee { double getCost(); } class SimpleCoffee implements Coffee { public double getCost() { return 10; } }abstract class CoffeeDecorator implements Coffee {protected Coffee coffee;public CoffeeDecorator(Coffee coffee) { this.coffee = coffee; } }class MilkDecorator extends CoffeeDecorator {public MilkDecorator(Coffee coffee) { super(coffee); }public double getCost() { return coffee.getCost() + 2; } }
3. 代理模式(Proxy)
-
定义:为其他对象提供一种代理以控制对这个对象的访问。
-
类型:
-
虚拟代理:延迟加载(如图片懒加载)。
-
保护代理:控制访问权限。
-
远程代理:跨网络访问对象(如RPC)。
-
-
应用场景:
-
Spring AOP中的动态代理(JDK动态代理、CGLIB)。
-
访问敏感资源时的权限校验。
-
-
代码示例:
interface Image { void display(); }class RealImage implements Image {public RealImage(String filename) { loadFromDisk(); }private void loadFromDisk() { /* 耗时操作 */ }public void display() { /* 显示图片 */ } }class ProxyImage implements Image {private RealImage realImage;private String filename;public ProxyImage(String filename) { this.filename = filename; }public void display() {if (realImage == null) realImage = new RealImage(filename);realImage.display();} }
4. 组合模式(Composite)
-
定义:将对象组合成树形结构以表示“部分-整体”层次,使客户端统一处理单个对象和组合对象。
-
结构:
-
组件接口(Component):定义叶子节点和容器的公共操作(如
add()
,remove()
)。 -
叶子节点(Leaf):无子节点,实现基础操作。
-
复合节点(Composite):包含子组件,管理子组件集合。
-
-
应用场景:
-
文件系统(文件与文件夹的统一操作)。
-
GUI容器控件(如Panel包含Button、Label等)。
-
-
代码示例:
interface FileSystemComponent {void display(); }class File implements FileSystemComponent {public void display() { System.out.println("显示文件"); } }class Folder implements FileSystemComponent {private List<FileSystemComponent> children = new ArrayList<>();public void add(FileSystemComponent cmp) { children.add(cmp); }public void display() {for (FileSystemComponent cmp : children) cmp.display();} }
5. 外观模式(Facade)
-
定义:为子系统中的一组接口提供一个一致的界面,简化客户端调用。
-
应用场景:
-
复杂API的简化封装(如支付系统的统一入口)。
-
微服务网关聚合多个服务接口。
-
-
代码示例:
class SubsystemA { void operationA() { /*...*/ } } class SubsystemB { void operationB() { /*...*/ } }class Facade {private SubsystemA a = new SubsystemA();private SubsystemB b = new SubsystemB();public void simplifiedOperation() {a.operationA();b.operationB();} }
6. 享元模式(Flyweight)
-
定义:运用共享技术有效地支持大量细粒度的对象。
-
关键点:
-
内部状态:可共享的部分(如字符的Unicode值)。
-
外部状态:不可共享的部分(如字符的位置、颜色)。
-
-
应用场景:
-
文本编辑器中的字符对象池。
-
游戏中的粒子系统(共享粒子类型,外部传入位置和速度)。
-
-
代码示例:
class Flyweight {private String intrinsicState; // 内部状态public Flyweight(String intrinsicState) { this.intrinsicState = intrinsicState; }public void operation(String extrinsicState) { /*...*/ } }class FlyweightFactory {private Map<String, Flyweight> pool = new HashMap<>();public Flyweight getFlyweight(String key) {if (!pool.containsKey(key)) pool.put(key, new Flyweight(key));return pool.get(key);} }
7. 桥接模式(Bridge)
-
定义:将抽象部分与实现部分分离,使它们可以独立变化。
-
结构:
-
抽象化(Abstraction):定义高层控制逻辑。
-
扩展抽象化(RefinedAbstraction):扩展抽象逻辑。
-
实现者(Implementor):定义底层实现接口。
-
具体实现者(ConcreteImplementor):实现具体功能。
-
-
应用场景:
-
跨平台图形渲染(如不同操作系统的绘图API)。
-
消息发送方式(邮件、短信)与内容类型的解耦。
-
-
代码示例:
interface Renderer { void renderCircle(float radius); } class VectorRenderer implements Renderer { /* 矢量渲染 */ } class RasterRenderer implements Renderer { /* 栅格渲染 */ }abstract class Shape {protected Renderer renderer;public Shape(Renderer renderer) { this.renderer = renderer; }abstract void draw(); }class Circle extends Shape {private float radius;public Circle(Renderer renderer, float radius) { super(renderer); this.radius = radius; }void draw() { renderer.renderCircle(radius); } }
3. 行为型模式
核心:对象间的通信与职责分配。
1. 模板方法模式(Template Method)
-
定义:
定义算法的骨架,将某些步骤延迟到子类实现,使得子类可以不改变算法结构即可重定义某些步骤。 -
结构:
-
抽象类(AbstractClass):定义模板方法(
final
修饰)和抽象步骤方法(如primitiveStep1()
)。 -
具体子类(ConcreteClass):实现抽象步骤。
-
-
应用场景:
-
框架设计(如Spring的
JdbcTemplate
)。 -
统一流程控制(如订单处理流程:验证→支付→发货)。
-
-
代码示例:
abstract class AbstractClass {public final void templateMethod() { // 模板方法step1();step2(); // 抽象步骤}void step1() { /* 默认实现 */ }abstract void step2(); }class ConcreteClass extends AbstractClass {void step2() { /* 子类实现 */ } }
2. 策略模式(Strategy)
-
定义:定义算法族,封装每个算法,使其可互相替换,让算法的变化独立于使用它的客户端。
-
结构:
-
策略接口(Strategy):定义算法方法(如
execute()
)。 -
具体策略类(ConcreteStrategy):实现不同算法。
-
上下文类(Context):持有策略对象并调用其算法。
-
-
应用场景:
-
支付方式选择(支付宝、微信支付等)。
-
排序算法切换(冒泡排序、快速排序)。
-
-
代码示例:
interface PaymentStrategy { void pay(int amount); }class AlipayStrategy implements PaymentStrategy {public void pay(int amount) { /* 支付宝支付逻辑 */ } }class Context {private PaymentStrategy strategy;public void setStrategy(PaymentStrategy strategy) { this.strategy = strategy; }public void executePay(int amount) { strategy.pay(amount); } }
3. 观察者模式(Observer)
-
定义:定义对象间的一对多依赖关系,当一个对象(主题)状态改变时,所有依赖它的对象(观察者)自动收到通知并更新。
-
结构:
-
主题接口(Subject):提供注册、删除、通知观察者的方法。
-
具体主题(ConcreteSubject):维护观察者列表,状态改变时通知所有观察者。
-
观察者接口(Observer):定义更新方法(如
update()
)。 -
具体观察者(ConcreteObserver):实现更新逻辑。
-
-
应用场景:
-
事件驱动系统(如GUI按钮点击事件)。
-
发布-订阅模型(如消息队列)。
-
-
代码示例:
interface Observer { void update(String message); }class ConcreteObserver implements Observer {public void update(String message) { /* 处理消息 */ } }class Subject {private List<Observer> observers = new ArrayList<>();public void addObserver(Observer o) { observers.add(o); }public void notifyObservers(String message) {for (Observer o : observers) o.update(message);} }
4. 责任链模式(Chain of Responsibility)
-
定义:使多个对象有机会处理请求,从而避免请求的发送者和接受者之前的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
-
结构:
-
处理器接口(Handler):定义处理请求的方法和设置下一个处理器的链接方法。
-
具体处理器(ConcreteHandler):实现处理逻辑,决定是否处理请求或传递给下一个处理器。
-
-
应用场景:
-
审批流程(如请假审批:组长→经理→CEO)。
-
异常处理链(如Spring MVC的拦截器)。
-
-
代码示例:
abstract class Handler {protected Handler next;public void setNext(Handler next) { this.next = next; }public abstract void handleRequest(Request request); }class ManagerHandler extends Handler {public void handleRequest(Request request) {if (canHandle(request)) { /* 处理 */ } else if (next != null) next.handleRequest(request);} }
5. 命令模式(Command)
-
定义:将请求封装为对象,以便支持请求的排队、记录、撤销等操作。
-
结构:
-
命令接口(Command):声明执行方法(如
execute()
)。 -
具体命令(ConcreteCommand):绑定接收者对象并调用其方法。
-
调用者(Invoker):触发命令执行(如按钮点击)。
-
接收者(Receiver):实际执行操作的对象。
-
-
应用场景:
-
图形界面菜单操作(撤销、重做)。
-
任务队列调度(如线程池任务提交)。
-
-
代码示例:
interface Command { void execute(); }class LightOnCommand implements Command {private Light light;public LightOnCommand(Light light) { this.light = light; }public void execute() { light.on(); } }class RemoteControl { // Invokerprivate Command command;public void setCommand(Command cmd) { this.command = cmd; }public void pressButton() { command.execute(); } }
6. 状态模式(State)
-
定义:允许对象在其内部状态改变时改变行为,将状态相关的逻辑封装到独立的状态类中。
-
结构:
-
状态接口(State):定义状态行为方法(如
handle()
)。 -
具体状态类(ConcreteState):实现不同状态下的行为。
-
上下文类(Context):持有状态对象,委托状态处理请求。
-
-
应用场景:
-
订单状态流转(待支付→已发货→已完成)。
-
游戏角色状态(正常、中毒、眩晕)。
-
-
代码示例:
interface State { void handle(Context context); }class ConcreteStateA implements State {public void handle(Context context) { context.setState(new ConcreteStateB());} }class Context {private State state;public void setState(State state) { this.state = state; }public void request() { state.handle(this); } }
7.解释器模式(Interpreter)
- 定义:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
- 代码示例:
// 抽象表达式 interface Expression {int interpret(Context context); }// 终结符表达式:数字 class Number implements Expression {private int value;public Number(int value) { this.value = value; }public int interpret(Context context) { return value; } }// 非终结符表达式:加法 class Add implements Expression {private Expression left;private Expression right;public Add(Expression left, Expression right) {this.left = left;this.right = right;}public int interpret(Context context) {return left.interpret(context) + right.interpret(context);} }// 非终结符表达式:乘法 class Multiply implements Expression {private Expression left;private Expression right;public Multiply(Expression left, Expression right) {this.left = left;this.right = right;}public int interpret(Context context) {return left.interpret(context) * right.interpret(context);} }// 上下文(此处简单实现,无额外状态) class Context {}// 客户端构建语法树并解释 public class Client {public static void main(String[] args) {// 表达式:1 + 2 * 3Expression expr = new Add(new Number(1),new Multiply(new Number(2), new Number(3)));Context context = new Context();System.out.println(expr.interpret(context)); // 输出:7} }
8. 中介者模式(Mediator Pattern)
定义:
中介者模式通过引入一个中介对象来封装一组对象之间的交互,减少对象间的直接依赖,使交互变得松散耦合。结构:
-
Mediator(中介者接口):定义对象间通信的接口。
-
ConcreteMediator(具体中介者):协调各对象间的交互,维护对同事对象的引用。
-
Colleague(同事类接口):定义同事对象的通用接口,每个同事对象知道其中介者。
-
ConcreteColleague(具体同事类):实现同事接口,通过中介者与其他同事通信。
-
对象间存在复杂的网状依赖关系(如GUI组件间的交互)。
-
需要集中控制多个对象间的通信逻辑。
代码示例(Java):
interface Mediator {void notify(Colleague sender, String event);
}class ChatRoom implements Mediator {private List<Colleague> users = new ArrayList<>();public void addUser(Colleague user) { users.add(user); }@Overridepublic void notify(Colleague sender, String message) {for (Colleague user : users) {if (user != sender) user.receive(message);}}
}abstract class Colleague {protected Mediator mediator;public Colleague(Mediator mediator) { this.mediator = mediator; }abstract void send(String message);abstract void receive(String message);
}class User extends Colleague {public User(Mediator mediator) { super(mediator); }@Overridepublic void send(String message) {System.out.println("发送消息: " + message);mediator.notify(this, message);}@Overridepublic void receive(String message) {System.out.println("接收消息: " + message);}
}// 客户端使用
public class Client {public static void main(String[] args) {ChatRoom chatRoom = new ChatRoom();User alice = new User(chatRoom);User bob = new User(chatRoom);chatRoom.addUser(alice);chatRoom.addUser(bob);alice.send("你好!"); // Bob接收消息}
}
9.备忘录模式(Memento Pattern)
定义:
备忘录模式在不破坏封装性的前提下,捕获对象的内部状态并保存,以便后续恢复。
结构:
-
Originator(原发器):需要保存状态的对象,提供创建备忘录和恢复状态的方法。
-
Memento(备忘录):存储原发器的状态(通常为不可变对象)。
-
Caretaker(管理者):负责保存和恢复备忘录,但不操作其内容。
适用场景:
-
需要实现撤销/重做功能(如文本编辑器的撤销操作)。
-
保存对象的历史状态用于回滚(如游戏存档)。
代码示例(Java):
// 原发器
class TextEditor {private String content;public void setContent(String content) { this.content = content; }public String getContent() { return content; }public Memento save() { return new Memento(content); }public void restore(Memento memento) { this.content = memento.getContent(); }
}// 备忘录
class Memento {private final String content;public Memento(String content) { this.content = content; }public String getContent() { return content; }
}// 管理者
class History {private List<Memento> mementos = new ArrayList<>();public void push(Memento memento) { mementos.add(memento); }public Memento pop() { return mementos.remove(mementos.size() - 1); }
}// 客户端使用
public class Client {public static void main(String[] args) {TextEditor editor = new TextEditor();History history = new History();editor.setContent("Version 1");history.push(editor.save());editor.setContent("Version 2");history.push(editor.save());editor.restore(history.pop()); // 回退到Version 1System.out.println(editor.getContent());}
}
10.访问者模式(Visitor Pattern)
定义:
访问者模式将作用于对象结构的操作与对象本身分离,允许在不修改对象结构的前提下定义新操作。
结构:
-
Visitor(访问者接口):声明访问对象结构中各元素的方法(如
visitElementA()
)。 -
ConcreteVisitor(具体访问者):实现访问者接口,定义具体操作。
-
Element(元素接口):定义接受访问者的方法(
accept(Visitor visitor)
)。 -
ConcreteElement(具体元素):实现元素接口,调用访问者的对应方法。
-
ObjectStructure(对象结构):维护元素集合,提供遍历接口。
适用场景:
-
需要对复杂对象结构进行多种独立操作(如编译器语法树分析)。
-
避免污染元素类的代码(如统计功能与业务逻辑分离)。
代码示例(Java):
interface Visitor {void visit(ElementA element);void visit(ElementB element);
}class ConcreteVisitor implements Visitor {@Overridepublic void visit(ElementA element) {System.out.println("处理ElementA: " + element.operationA());}@Overridepublic void visit(ElementB element) {System.out.println("处理ElementB: " + element.operationB());}
}interface Element {void accept(Visitor visitor);
}class ElementA implements Element {public String operationA() { return "操作A"; }@Overridepublic void accept(Visitor visitor) { visitor.visit(this); }
}class ElementB implements Element {public String operationB() { return "操作B"; }@Overridepublic void accept(Visitor visitor) { visitor.visit(this); }
}// 客户端使用
public class Client {public static void main(String[] args) {List<Element> elements = Arrays.asList(new ElementA(), new ElementB());Visitor visitor = new ConcreteVisitor();for (Element element : elements) {element.accept(visitor);}}
}
11.迭代器模式(Iterator Pattern)
定义:迭代器模式是一种行为型设计模式,提供一种方法顺序访问聚合对象中的元素,而无需暴露其底层表示。核心思想是将遍历逻辑从聚合对象中分离,实现数据存储与遍历解耦。
-
Aggregate(聚合接口):声明
createIterator()
方法,返回一个迭代器对象。 -
ConcreteAggregate(具体聚合类):实现聚合接口,返回与自身数据结构匹配的具体迭代器实例(如
new ConcreteIterator(this)
)。 -
Iterator(迭代器接口):定义遍历方法:
-
hasNext()
:判断是否还有下一个元素。 -
next()
:移动游标并返回当前元素。 -
currentItem()
(可选):直接获取当前元素,不移动游标。
-
-
ConcreteIterator(具体迭代器):实现迭代器接口,维护当前遍历位置(如
currentIndex
),并与聚合对象交互以访问元素。