明白了!我帮你系统地整理 Java 23种设计模式,每个模式都包含:
- 概述
- UML 简图(文字版)
- Java 代码示例
- 适用场景
- 优缺点简述
这是一个非常完整的学习资料,篇幅较长,我分模块给你呈现,每个分类分几条消息发给你,方便你吸收和复查。
Java 23种设计模式 全面详解(创建型部分)
1. 单例模式(Singleton)
概述
确保一个类只有一个实例,并提供全局访问点。
UML 简图(文字)
+---------------------+
| Singleton |
+---------------------+
| - instance: Singleton|
+---------------------+
| + getInstance(): Singleton |
+---------------------+
Java代码示例
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;
}
}
适用场景
- 需要全局唯一对象,例如配置管理器、线程池、缓存管理
优缺点
- 优点:节省资源,避免重复实例
- 缺点:过度使用会导致代码耦合,不利于测试
2. 工厂方法模式(Factory Method)
概述
定义创建对象的接口,让子类决定实例化哪一个类。
UML 简图
+-------------+ +---------------+
| Factory |<>---------| Product |
+-------------+ +---------------+
| + createProduct() | + use() |
+-------------+ +---------------+
^
|
+-------------------+
| ConcreteFactory |
+-------------------+
| + createProduct() |
+-------------------+
+-------------------+
| ConcreteProduct |
+-------------------+
| + use() |
+-------------------+
Java代码示例
// 产品接口
public interface Product {
void use();
}
// 具体产品
public class ConcreteProduct implements Product {
public void use() {
System.out.println("使用具体产品");
}
}
// 工厂抽象类
public abstract class Factory {
public abstract Product createProduct();
}
// 具体工厂
public class ConcreteFactory extends Factory {
public Product createProduct() {
return new ConcreteProduct();
}
}
适用场景
- 系统需要独立于产品创建和使用时
- 增加新产品时符合开闭原则
优缺点
- 优点:封装对象创建,符合单一职责
- 缺点:每增加产品都要增加工厂类,类增多
3. 抽象工厂模式(Abstract Factory)
概述
提供创建一系列相关或依赖对象的接口,而无需指定具体类。
UML 简图
+-------------------+ +------------------+
| AbstractFactory |<>---------| AbstractProductA |
+-------------------+ +------------------+
| + createProductA()| | + use() |
| + createProductB()| +------------------+
+-------------------+
^
|
+-------------------------+
| ConcreteFactory1 |
+-------------------------+
| + createProductA() |
| + createProductB() |
+-------------------------+
+------------------+ +------------------+
| ConcreteProductA1 | | ConcreteProductB1 |
+------------------+ +------------------+
Java代码示例
// 抽象产品A
interface ProductA {
void use();
}
// 抽象产品B
interface ProductB {
void eat();
}
// 具体产品A1
class ProductA1 implements ProductA {
public void use() { System.out.println("使用产品A1"); }
}
// 具体产品B1
class ProductB1 implements ProductB {
public void eat() { System.out.println("吃产品B1"); }
}
// 抽象工厂
interface AbstractFactory {
ProductA createProductA();
ProductB createProductB();
}
// 具体工厂1
class ConcreteFactory1 implements AbstractFactory {
public ProductA createProductA() { return new ProductA1(); }
public ProductB createProductB() { return new ProductB1(); }
}
适用场景
- 产品族较多,且需要一起使用
- 系统要独立于产品创建和使用
优缺点
- 优点:易于交换产品族,保证产品间一致性
- 缺点:产品族扩展困难
4. 建造者模式(Builder)
概述
将复杂对象的构建与表示分离,使同样构建过程可创建不同表示。
UML 简图
+-------------+ +-----------------+
| Director |----->| Builder |
+-------------+ +-----------------+
/ | \
+----------------+ +------------+ +--------------+
| ConcreteBuilder| | Product | | buildPart() |
+----------------+ +------------+ +--------------+
Java代码示例
class Product {
private String partA;
private String partB;
public void setPartA(String partA) { this.partA = partA; }
public void setPartB(String partB) { this.partB = partB; }
public void show() {
System.out.println("部件A: " + partA);
System.out.println("部件B: " + partB);
}
}
abstract class Builder {
protected Product product = new Product();
public abstract void buildPartA();
public abstract void buildPartB();
public Product getResult() { return product; }
}
class ConcreteBuilder extends Builder {
public void buildPartA() { product.setPartA("部件A的具体实现"); }
public void buildPartB() { product.setPartB("部件B的具体实现"); }
}
class Director {
private Builder builder;
public Director(Builder builder) { this.builder = builder; }
public void construct() {
builder.buildPartA();
builder.buildPartB();
}
}
public class Client {
public static void main(String[] args) {
Builder builder = new ConcreteBuilder();
Director director = new Director(builder);
director.construct();
Product product = builder.getResult();
product.show();
}
}
适用场景
- 创建复杂对象,构造步骤稳定但部件可变
- 产品需要多种表现
优缺点
- 优点:解耦复杂对象构造与表示
- 缺点:增加类和对象复杂度
5. 原型模式(Prototype)
概述
通过复制已有实例创建新对象,避免重新初始化开销。
UML 简图
+-------------+
| Prototype |
+-------------+
| + clone() |
+-------------+
+-----------------+
| ConcretePrototype|
+-----------------+
| + clone() |
+-----------------+
Java代码示例
public class Prototype implements Cloneable {
private String field;
public Prototype(String field) {
this.field = field;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getField() {
return field;
}
}
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
Prototype p1 = new Prototype("原型对象");
Prototype p2 = (Prototype) p1.clone();
System.out.println(p2.getField());
}
}
适用场景
- 对象创建成本较大,需要频繁复制
- 复杂对象避免重复初始化
优缺点
- 优点:提高性能,简化对象创建
- 缺点:深拷贝复杂,可能导致隐藏问题
好的!接下来继续为你详细讲解 结构型设计模式,包含7种设计模式,每个模式都配有概述、UML文字简图、Java示例代码、适用场景和优缺点。
Java 23种设计模式 全面详解(结构型部分)
6. 适配器模式(Adapter)
概述
将一个类的接口转换成客户希望的另一个接口,使得原本接口不兼容的类可以一起工作。
UML简图
+-------------+ +----------------+
| Target |<---------| Adapter |
+-------------+ +----------------+
| + request() | | + request() |
+-------------+ +----------------+
|
+----------------+
| Adaptee |
| + specificRequest() |
+----------------+
Java代码示例
// 目标接口
interface Target {
void request();
}
// 需要适配的类
class Adaptee {
public void specificRequest() {
System.out.println("被适配者的方法被调用");
}
}
// 适配器类,实现目标接口,内部调用被适配者的方法
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
adaptee.specificRequest();
}
}
public class Client {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request();
}
}
适用场景
- 系统需要使用某些现有类,但接口不符合需求
- 需要复用现有类而不想修改其代码
优缺点
- 优点:提高类的复用性,灵活性好
- 缺点:增加系统复杂度,适配器过多可能难维护
7. 桥接模式(Bridge)
概述
将抽象部分与实现部分分离,使它们都可以独立变化。
UML简图
+-------------+ +----------------+
| Abstraction |<>-------->| Implementor |
+-------------+ +----------------+
| - implementor| | + operation() |
| + operation()| +----------------+
+-------------+
+-------------------+ +------------------+
| RefinedAbstraction | | ConcreteImplementor|
+-------------------+ +------------------+
Java代码示例
// 实现化角色接口
interface Implementor {
void operationImpl();
}
// 具体实现化角色A
class ConcreteImplementorA implements Implementor {
public void operationImpl() {
System.out.println("具体实现A的操作");
}
}
// 抽象化角色
abstract class Abstraction {
protected Implementor implementor;
protected Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
// 扩充抽象化角色
class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
public void operation() {
implementor.operationImpl();
}
}
public class Client {
public static void main(String[] args) {
Implementor impl = new ConcreteImplementorA();
Abstraction abs = new RefinedAbstraction(impl);
abs.operation();
}
}
适用场景
- 抽象和实现需要独立变化时
- 希望在不修改抽象接口的情况下扩展实现
优缺点
- 优点:提高系统灵活性,符合开闭原则
- 缺点:增加系统复杂度
8. 组合模式(Composite)
概述
将对象组合成树形结构以表示“部分-整体”的层次结构,使客户端可一致地处理单个对象和组合对象。
UML简图
+----------------+
| Component |
+----------------+
| + operation() |
+----------------+
/ \
+---------+ +-----------+
| Leaf | | Composite |
+---------+ +-----------+
| +operation() |
| -children: List<Component> |
+-----------------------+
Java代码示例
import java.util.ArrayList;
import java.util.List;
// 抽象组件
abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void operation();
}
// 叶子节点
class Leaf extends Component {
public Leaf(String name) {
super(name);
}
public void operation() {
System.out.println("叶子 " + name + " 被访问");
}
}
// 容器节点
class Composite extends Component {
private List<Component> children = new ArrayList<>();
public Composite(String name) {
super(name);
}
public void add(Component c) {
children.add(c);
}
public void remove(Component c) {
children.remove(c);
}
public void operation() {
System.out.println("容器 " + name + " 被访问");
for (Component c : children) {
c.operation();
}
}
}
public class Client {
public static void main(String[] args) {
Composite root = new Composite("根节点");
Leaf leaf1 = new Leaf("叶子1");
Leaf leaf2 = new Leaf("叶子2");
Composite branch = new Composite("枝节点");
Leaf leaf3 = new Leaf("叶子3");
root.add(leaf1);
root.add(branch);
branch.add(leaf2);
branch.add(leaf3);
root.operation();
}
}
适用场景
- 表示对象的部分-整体层次结构
- 客户端忽略单个对象与组合对象的不同
优缺点
- 优点:客户端代码简洁,统一对待叶子和容器
- 缺点:设计较复杂,层次过深影响性能
9. 装饰模式(Decorator)
概述
动态地给对象添加额外职责,是继承的替代方案。
UML简图
+--------------+ +-----------------+
| Component |<----------| Decorator |
+--------------+ +-----------------+
| + operation()| | - component: Component |
+--------------+ | + operation() |
+-----------------+
+-----------------+
| ConcreteDecorator|
+-----------------+
Java代码示例
// 抽象组件
interface Component {
void operation();
}
// 具体组件
class ConcreteComponent implements Component {
public void operation() {
System.out.println("具体组件的操作");
}
}
// 抽象装饰类
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
// 具体装饰
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("具体装饰类的附加操作");
}
}
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component decorated = new ConcreteDecorator(component);
decorated.operation();
}
}
适用场景
- 需要扩展对象功能,且不想使用继承
- 动态增加职责
优缺点
- 优点:灵活,动态扩展功能
- 缺点:过多装饰层次导致理解困难
10. 外观模式(Facade)
概述
为复杂子系统提供一个统一接口,使子系统更易使用。
UML简图
+-------------+
| Facade |
+-------------+
| + operation()|
+-------------+
/ | \
SubsystemA SubsystemB SubsystemC
Java代码示例
// 子系统类A
class SubsystemA {
public void operationA() {
System.out.println("子系统A操作");
}
}
// 子系统类B
class SubsystemB {
public void operationB() {
System.out.println("子系统B操作");
}
}
// 外观类
class Facade {
private SubsystemA subsystemA;
private SubsystemB subsystemB;
public Facade() {
subsystemA = new SubsystemA();
subsystemB = new SubsystemB();
}
public void operation() {
subsystemA.operationA();
subsystemB.operationB();
}
}
public class Client {
public static void main(String[] args) {
Facade facade = new Facade();
facade.operation();
}
}
适用场景
- 简化复杂子系统调用
- 提供一个高层接口调用多个子系统
优缺点
- 优点:减少依赖,简化调用
- 缺点:不符合开闭原则,系统复杂时外观类可能庞大
11. 享元模式(Flyweight)
概述
通过共享技术有效支持大量细粒度对象,减少内存占用。
UML简图
+-------------+
| Flyweight |
+-------------+
| + operation()|
+-------------+
+-----------------+
| ConcreteFlyweight|
+-----------------+
| + operation() |
+-----------------+
+-----------------+
| FlyweightFactory|
+-----------------+
| - pool: Map |
| + getFlyweight()|
+-----------------+
Java代码示例
import java.util.Hash
发表回复