Java设计模式
设计模式概述
设计模式是软件开发中针对反复出现问题总结出的通用解决方案。根据目的和结构,设计模式可分为创建型、结构型和行为型三类。以下是 Java 中 23 种设计模式的分类及示例:
一、创建型模式(5 种)
1. 单例模式(Singleton)
确保一个类只有一个实例,并提供全局访问点。
public class Singleton {private static final Singleton INSTANCE = new Singleton();private Singleton() {} // 私有构造函数public static Singleton getInstance() {return INSTANCE;}
}
2. 工厂模式(Factory Method)
定义创建对象的接口,让子类决定实例化哪个类。
// 产品接口
interface Product { void operation(); }// 具体产品
class ConcreteProductA implements Product {@Override public void operation() { System.out.println("Product A"); }
}// 工厂类
class Factory {public Product createProduct(String type) {if ("A".equals(type)) return new ConcreteProductA();return null;}
}
3. 抽象工厂模式(Abstract Factory)
提供创建一系列相关对象的接口,无需指定具体类。
// 抽象工厂
interface GUIFactory {Button createButton();Checkbox createCheckbox();
}// Windows工厂
class WindowsFactory implements GUIFactory {@Override public Button createButton() { return new WindowsButton(); }@Override public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}
4. 建造者模式(Builder)
将复杂对象的构建与表示分离,允许相同构建过程创建不同表示。
class Car {private String engine;private String wheels;// getters/settersstatic class Builder {private String engine;private String wheels;public Builder engine(String engine) {this.engine = engine;return this;}public Car build() {Car car = new Car();car.engine = this.engine;car.wheels = this.wheels;return car;}}
}
5. 原型模式(Prototype)
通过复制现有实例创建新对象,无需知道创建细节。
interface Prototype {Prototype clone();
}class ConcretePrototype implements Prototype {@Overridepublic Prototype clone() {try {return (Prototype) super.clone();} catch (CloneNotSupportedException e) {return null;}}
}
二、结构型模式(7 种)
6. 适配器模式(Adapter)
将一个类的接口转换成用户期望的另一个接口。
// 目标接口
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; }@Override public void request() { adaptee.specificRequest(); }
}
7. 桥接模式(Bridge)
将抽象部分与实现部分分离,使它们可以独立变化。
// 实现接口
interface Color { void applyColor(); }// 抽象类
abstract class Shape {protected Color color;public Shape(Color color) { this.color = color; }abstract void draw();
}// 具体实现
class RedColor implements Color {@Override public void applyColor() { System.out.println("红色"); }
}
8. 组合模式(Composite)
将对象组合成树形结构以表示 “部分 - 整体” 的层次结构。
// 组件接口
interface Component { void operation(); }// 叶子节点
class Leaf implements Component {@Override public void operation() { System.out.println("叶子操作"); }
}// 容器节点
class Composite implements Component {private List<Component> children = new ArrayList<>();@Override public void operation() { children.forEach(Component::operation); }public void add(Component c) { children.add(c); }
}
9. 装饰器模式(Decorator)
动态地给对象添加额外职责,比继承更灵活。
// 组件接口
interface Beverage { String getDescription(); double cost(); }// 具体组件
class Espresso implements Beverage {@Override public String getDescription() { return "Espresso"; }@Override public double cost() { return 1.99; }
}// 装饰器基类
abstract class CondimentDecorator implements Beverage {protected Beverage beverage;
}
10. 外观模式(Facade)
为子系统中的一组接口提供统一高层接口,简化客户端使用。
class SubsystemA { public void operationA() { System.out.println("系统A操作"); } }
class SubsystemB { public void operationB() { System.out.println("系统B操作"); } }class Facade {private SubsystemA a = new SubsystemA();private SubsystemB b = new SubsystemB();public void operation() {a.operationA();b.operationB();}
}
11. 享元模式(Flyweight)
通过共享技术有效支持大量细粒度对象。
// 享元接口
interface Flyweight { void operation(int extrinsicState); }// 具体享元
class ConcreteFlyweight implements Flyweight {private final String intrinsicState;public ConcreteFlyweight(String state) { this.intrinsicState = state; }@Override public void operation(int extrinsicState) {System.out.printf("内蕴状态: %s, 外蕴状态: %d%n", intrinsicState, extrinsicState);}
}
12. 代理模式(Proxy)
为其他对象提供一种代理以控制对这个对象的访问。
// 主题接口
interface Subject { void request(); }// 真实主题
class RealSubject implements Subject {@Override public void request() { System.out.println("真实请求"); }
}// 代理主题
class Proxy implements Subject {private RealSubject realSubject;@Override public void request() {if (realSubject == null) realSubject = new RealSubject();preRequest();realSubject.request();postRequest();}
}
三、行为型模式(11 种)
13. 责任链模式(Chain of Responsibility)
使多个对象都有机会处理请求,避免请求发送者和接收者的耦合。
// 处理者接口
abstract class Handler {protected Handler successor;public void setSuccessor(Handler successor) { this.successor = successor; }public abstract void handleRequest(int request);
}// 具体处理者
class ConcreteHandler1 extends Handler {@Override public void handleRequest(int request) {if (request < 10) System.out.println("处理请求: " + request);else if (successor != null) successor.handleRequest(request);}
}
14. 命令模式(Command)
将请求封装为对象,使你可以用不同请求参数化客户端。
// 命令接口
interface Command { void execute(); }// 接收者
class Receiver {public void action() { System.out.println("执行操作"); }
}// 具体命令
class ConcreteCommand implements Command {private Receiver receiver;@Override public void execute() { receiver.action(); }
}
15. 解释器模式(Interpreter)
给定语言,定义其文法表示,并定义解释器解释该文法。
// 表达式接口
interface Expression { int interpret(); }// 终结符表达式
class Number implements Expression {private final int number;public Number(int number) { this.number = number; }@Override public int interpret() { return number; }
}// 非终结符表达式
class Add implements Expression {private final Expression left;private final Expression right;@Override public int interpret() { return left.interpret() + right.interpret(); }
}
16. 迭代器模式(Iterator)
提供一种方法顺序访问一个聚合对象中的各个元素。
// 迭代器接口
interface Iterator<T> {boolean hasNext();T next();
}// 集合接口
interface Aggregate<T> {Iterator<T> createIterator();
}// 具体集合
class ConcreteAggregate implements Aggregate<String> {private final List<String> items = new ArrayList<>();@Override public Iterator<String> createIterator() { return new ConcreteIterator(items); }
}
17. 中介者模式(Mediator)
定义一个中介对象封装一系列对象交互,使各对象间松耦合。
// 中介者接口
interface Mediator {void send(String message, Colleague colleague);
}// 同事类
abstract class Colleague {protected Mediator mediator;public Colleague(Mediator mediator) { this.mediator = mediator; }public abstract void send(String message);public abstract void receive(String message);
}
18. 备忘录模式(Memento)
在不破坏封装性的前提下,捕获对象内部状态并保存。
// 备忘录
class Memento {private final String state;public Memento(String state) { this.state = state; }public String getState() { return state; }
}// 原发器
class Originator {private String state;public void setState(String state) { this.state = state; }public Memento saveStateToMemento() { return new Memento(state); }public void getStateFromMemento(Memento memento) { state = memento.getState(); }
}
19. 观察者模式(Observer)
定义对象间一对多依赖关系,当一个对象状态变化时,所有依赖者被通知。
// 主题接口
interface Subject {void registerObserver(Observer o);void removeObserver(Observer o);void notifyObservers();
}// 观察者接口
interface Observer {void update(int temperature);
}
20. 状态模式(State)
允许对象在内部状态改变时改变行为,看起来像修改了类。
// 状态接口
interface State { void handle(); }// 上下文
class Context {private State state;public void setState(State state) { this.state = state; }public void request() { state.handle(); }
}
21. 策略模式(Strategy)
定义一系列算法,将每个算法封装,并使它们可以互换。
// 策略接口
interface Strategy { int doOperation(int num1, int num2); }// 具体策略
class AddStrategy implements Strategy {@Override public int doOperation(int num1, int num2) { return num1 + num2; }
}// 上下文
class Context {private Strategy strategy;public int executeStrategy(int num1, int num2) {return strategy.doOperation(num1, num2);}
}
22. 模板方法模式(Template Method)
定义算法骨架,将一些步骤延迟到子类实现。
// 抽象类
abstract class Game {abstract void initialize();abstract void startPlay();abstract void endPlay();// 模板方法public final void play() {initialize();startPlay();endPlay();}
}
23. 访问者模式(Visitor)
表示作用于某对象结构中各元素的操作,使你可以在不改变元素类的前提下定义新操作。
// 元素接口
interface Element { void accept(Visitor visitor); }// 具体元素
class ConcreteElementA implements Element {@Override public void accept(Visitor visitor) { visitor.visit(this); }public String operationA() { return "具体元素A的操作"; }
}// 访问者接口
interface Visitor {void visit(ConcreteElementA element);void visit(ConcreteElementB element);
}
总结
设计模式是软件设计的重要工具,合理使用可提高代码的可维护性、可扩展性和可复用性。实际开发中应根据需求选择合适的模式,避免过度设计。