设计模式是软件开发中为了提高代码的可重用性和可维护性,解决特定问题而总结出的最佳实践。在Java中,有23种经典的设计模式,大致可以分为三类:创建型、结构型和行为型。
创建型模式
-
单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供一个全局访问点。
```java public class Singleton { private static Singleton instance;private Singleton() {}
public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ```
-
工厂方法模式(Factory Method Pattern)
工厂方法模式定义一个创建对象的接口,让子类决定实例化哪一个类。
```java interface Product { void use(); }
class ConcreteProductA implements Product { public void use() { System.out.println("使用产品A"); } }
class ProductFactory { public Product createProduct(String type) { if (type.equals("A")) { return new ConcreteProductA(); } return null; } } ```
- 抽象工厂模式(Abstract Factory Pattern)
抽象工厂模式提供一个创建相关或相互依赖对象的接口。
```java interface AbstractFactory { ProductA createProductA(); ProductB createProductB(); }
class ConcreteFactory1 implements AbstractFactory { public ProductA createProductA() { return new ProductA1(); } public ProductB createProductB() { return new ProductB1(); } } ```
- 建造者模式(Builder Pattern)
建造者模式用于构建一个复杂对象的各个部分。
```java class Product { private String partA; private String partB; // getters and setters }
class ProductBuilder { private Product product = new Product();
public ProductBuilder buildPartA(String partA) {
product.setPartA(partA);
return this;
}
public ProductBuilder buildPartB(String partB) {
product.setPartB(partB);
return this;
}
public Product build() {
return product;
}
} ```
-
原型模式(Prototype Pattern)
原型模式用于通过复制现有的实例来创建新实例。
```java class Prototype implements Cloneable { private String attribute;@Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } ```
结构型模式
- 适配器模式(Adapter Pattern)
适配器模式使不兼容的接口可以协同工作。
```java class Adaptee { void specificRequest() { System.out.println("特定请求"); } }
interface Target { void request(); }
class Adapter implements Target { private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
} ```
- 桥接模式(Bridge Pattern)
桥接模式将抽象部分与其实现部分分离,使它们可以独立变化。
```java interface Implementor { void operation(); }
class ConcreteImplementorA implements Implementor { public void operation() { System.out.println("实现A"); } }
abstract class Abstraction { protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
abstract void operation();
} ```
- 组合模式(Composite Pattern)
组合模式将对象组合成树形结构以表示部分和整体的层次结构。
```java interface Component { void operation(); }
class Leaf implements Component { public void operation() { System.out.println("叶子节点"); } }
class Composite implements Component {
private List
public void add(Component component) {
children.add(component);
}
public void operation() {
for (Component child : children) {
child.operation();
}
}
} ```
- 装饰者模式(Decorator Pattern)
装饰者模式允许向现有对象添加新功能。
```java interface Component { void operation(); }
class ConcreteComponent implements Component { public void operation() { System.out.println("标准功能"); } }
class Decorator implements Component { protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
System.out.println("增加的功能");
}
} ```
-
外观模式(Facade Pattern)
外观模式为子系统提供一个简化的接口。
```java class SubsystemA { public void operationA() { System.out.println("子系统A的操作"); } }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(); }
} ```
-
享元模式(Flyweight Pattern)
享元模式通过共享对象来有效地支持大量细粒度的对象。
```java class Flyweight { private String intrinsicState;public Flyweight(String intrinsicState) { this.intrinsicState = intrinsicState; } public void operation(String extrinsicState) { System.out.println("内部状态: " + intrinsicState + ", 外部状态: " + extrinsicState); }
}
class FlyweightFactory { private Map
flyweights = new HashMap<>(); public Flyweight getFlyweight(String key) { if (!flyweights.containsKey(key)) { flyweights.put(key, new Flyweight(key)); } return flyweights.get(key); }
} ```
-
代理模式(Proxy Pattern)
代理模式为其他对象提供一种代理以控制对这个对象的访问。
```java interface Subject { void request(); }class RealSubject implements Subject { public void request() { System.out.println("真实主题的请求"); } }
class Proxy implements Subject { private RealSubject realSubject;
public void request() { if (realSubject == null) { realSubject = new RealSubject(); } realSubject.request(); }
} ```
行为型模式
-
责任链模式(Chain of Responsibility Pattern)
责任链模式将请求的发送者和接收者解耦,形成一个处理请求的链。
```java abstract class Handler { protected Handler next;public void setNext(Handler next) { this.next = next; } public abstract void handleRequest(int request);
}
class ConcreteHandlerA extends Handler { public void handleRequest(int request) { if (request < 10) { System.out.println("处理请求A: " + request); } else if (next != null) { next.handleRequest(request); } } } ```
-
命令模式(Command Pattern)
命令模式将请求封装为对象,使你可以用不同的请求对客户进行参数化。
```java interface Command { void execute(); }class ConcreteCommand implements Command { private Receiver receiver;
public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } public void execute() { receiver.action(); }
}
class Receiver { public void action() { System.out.println("执行请求"); } }
class Invoker { private Command command;
public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.execute(); }
} ```
-
解释器模式(Interpreter Pattern)
解释器模式用于给定一门语言,定义一个表示该语言句子的文法,并提供一个解释程序。
```java interface Expression { int interpret(); }class NumberExpression implements Expression { private int number;
public NumberExpression(int number) { this.number = number; } public int interpret() { return number; }
}
class AddExpression implements Expression { private Expression left; private Expression right;
public AddExpression(Expression left, Expression right) { this.left = left; this.right = right; } public int interpret() { return left.interpret() + right.interpret(); }
} ```
-
迭代器模式(Iterator Pattern)
迭代器模式提供一种顺序访问集合对象的方法,而不暴露其内部表示。
```java interface Iterator { boolean hasNext(); Object next(); }interface Aggregate { Iterator createIterator(); }
class ConcreteAggregate implements Aggregate { private List