总是记不住设计模式呢,做个笔记加强记忆。
一、设计模式概述
- 定义
设计模式是解决软件设计问题的可复用方案,描述在特定场景下如何组织代码结构和对象交互,以提高系统的灵活性、可维护性和可扩展性。 - 核心价值
○ 代码复用:避免重复造轮子。
○ 解耦:分离变化部分与稳定部分。
○ 标准化:提供行业通用的设计语言。 - 分类
○ 创建型模式:关注对象的创建机制(如工厂、单例)。
○ 结构型模式:通过组合对象形成更大结构(如适配器、代理)。
○ 行为型模式:定义对象间的协作与责任分配(如观察者、策略)。
二、创建型模式
工厂方法(Factory Method)
○ 定义:定义一个创建对象的接口,由子类决定实例化哪个类。
○ 应用场景:需要动态切换对象类型(如数据库连接器、日志记录器)。
○ 结构:
interface Product {}
class ConcreteProductA implements Product {}
class ConcreteProductB implements Product {}
abstract class Creator {
abstract Product createProduct();
}
class ConcreteCreatorA extends Creator {
Product createProduct() { return new ConcreteProductA(); }
}
○ 优点:解耦客户端与具体产品类。
a. 缺点:每新增一种产品需新增一个工厂类。
抽象工厂(Abstract Factory)
● 定义:创建一组相关或依赖对象的接口,无需指定具体类。
● 应用场景:跨平台UI组件(如Windows和Mac的按钮、文本框)。
● 结构:
interface Button {}
interface TextBox {}
class WinButton implements Button {}
class MacButton implements Button {}
interface GUIFactory {
Button createButton();
TextBox createTextBox();
}
class WinFactory implements GUIFactory { /*...*/ }
○ 优点:保证产品族的一致性。
○ 缺点:扩展新产品族困难。
单例(Singleton)
● 定义:确保一个类仅有一个实例,并提供全局访问点。
● 应用场景:配置管理类、线程池、数据库连接池。
● 实现方式:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
// 或使用双重检查锁定(Double-Check Locking)
○ 优点:节省资源,控制共享访问。
○ 缺点:需处理多线程安全问题。
建造者(Builder)
● 定义:将复杂对象的构造过程分解为多个步骤,允许按需生成不同表示形式。
● 应用场景:构造包含多个部件的复杂对象(如HTML文档生成器)。
● 结构:
class Product {
private String partA;
private String partB;
// Setters
}
interface Builder {
void buildPartA();
void buildPartB();
Product getResult();
}
class ConcreteBuilder implements Builder { /*...*/ }
class Director {
public Product construct(Builder builder) {
builder.buildPartA();
builder.buildPartB();
return builder.getResult();
}
}
○ 优点:封装复杂构造过程,支持不同配置。
○ 缺点:代码量增加。
三、结构型模式
适配器(Adapter)
○ 定义:将一个类的接口转换为客户端期望的另一个接口。
○ 应用场景:整合第三方库、旧系统兼容。
○ 分类:
● 类适配器:通过继承适配类(需多继承,Java不支持)。
● 对象适配器:通过组合适配对象(推荐)。
结构:
interface Target {
void request();
}
class Adaptee {
void specificRequest() { /*...*/ }
}
class Adapter implements Target {
private Adaptee adaptee;
Adapter(Adaptee adaptee) { this.adaptee = adaptee; }
public void request() { adaptee.specificRequest(); }
}
○ 优点:复用现有代码,灵活解耦。
○ 缺点:过多适配器会增加系统复杂度。
代理(Proxy)
● 定义:为其他对象提供一个代理以控制对该对象的访问。
● 应用场景:远程代理(RPC)、虚拟代理(延迟加载)、保护代理(权限控制)。
● 结构:
interface Subject {
void doAction();
}
class RealSubject implements Subject {
public void doAction() { /*...*/ }
}
class Proxy implements Subject {
private RealSubject realSubject;
public void doAction() {
if (realSubject == null) {
realSubject = new RealSubject();
}
realSubject.doAction();
}
}
○ 优点:增强对象访问控制。
○ 缺点:可能引入性能开销。
装饰器(Decorator)
● 定义:动态地为对象添加额外职责,比继承更灵活。
● 应用场景:Java I/O流(如BufferedInputStream)。
● 结构:
interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() { /*...*/ }
}
abstract class Decorator implements Component {
protected Component component;
Decorator(Component component) { this.component = component; }
public void operation() { component.operation(); }
}
class ConcreteDecoratorA extends Decorator {
ConcreteDecoratorA(Component component) { super(component); }
public void operation() {
super.operation();
addBehavior();
}
private void addBehavior() { /*...*/ }
}
○ 优点:避免类爆炸,支持运行时扩展。
○ 缺点:多层装饰会增加调试难度。
四、行为型模式
观察者(Observer)
● 定义:定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖对象自动更新。
● 应用场景:事件驱动系统(如GUI按钮点击、消息队列订阅)。
● 结构:
interface Observer {
void update(String message);
}
interface Subject {
void registerObserver(Observer o);
void notifyObservers(String message);
}
class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
public void registerObserver(Observer o) { observers.add(o); }
public void notifyObservers(String message) {
for (Observer o : observers) {
o.update(message);
}
}
}
○ 优点:松耦合,支持广播通信。
○ 缺点:可能因循环依赖导致死锁。
策略(Strategy)
● 定义:定义一系列算法,封装每个算法,并使它们可互换。
● 应用场景:支付方式选择(支付宝、微信、信用卡)。
● 结构:
interface Strategy {
void execute();
}
class ConcreteStrategyA implements Strategy {
public void execute() { /*...*/ }
}
class Context {
private Strategy strategy;
void setStrategy(Strategy strategy) { this.strategy = strategy; }
void executeStrategy() { strategy.execute(); }
}
○ 优点:算法独立变化,避免条件分支。
○ 缺点:客户端需了解不同策略差异。
模板方法(Template Method)
● 定义:在父类中定义算法骨架,允许子类重写某些步骤。
● 应用场景:框架设计(如Spring的JdbcTemplate)。
● 结构:
abstract class AbstractClass {
public void templateMethod() {
step1();
step2();
}
abstract void step1();
abstract void step2();
}
class ConcreteClass extends AbstractClass {
void step1() { /*...*/ }
void step2() { /*...*/ }
}
○ 优点:代码复用,控制扩展点。
○ 缺点:可能因过多抽象步骤导致理解困难。
五、高频考点与对比
模式对比
工厂方法 vs 抽象工厂:
● 工厂方法针对单一产品,抽象工厂针对产品族。
代理 vs 装饰器:
● 代理控制访问,装饰器增强功能。
应用场景分析题
题目示例:
● 场景:一个电商系统需要支持多种支付方式,且未来可能新增支付渠道。
● 解决方案:使用策略模式,将每种支付方式封装为独立策略类。
设计模式在架构中的应用
微服务架构:
● 网关模式(API Gateway)是门面模式的扩展。
● 服务发现机制依赖观察者模式。
核心模式:重点掌握单例、工厂、适配器、观察者、策略、模板方法。
605

被折叠的 条评论
为什么被折叠?



