设计模式-Java
一、创建型模式
1. 单例模式
定义
确保一个类只有一个实例,并提供一个全局访问点。
实现方式
-
饿汉式(线程安全,但可能浪费资源)
public class Singleton { // 静态变量,类加载时初始化 private static final Singleton instance = new Singleton(); // 私有构造方法,防止外部实例化 private Singleton() {} // 提供全局访问点 public static Singleton getInstance() { return instance; } // 示例方法 public void showMessage() { System.out.println("Hello from Singleton!"); } } // 测试类 public class TestSingleton { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); singleton.showMessage(); } }
-
懒汉式(延迟加载,需考虑线程安全)
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 void showMessage() { System.out.println("Hello from Lazy Singleton!"); } } // 测试类 public class TestSingleton { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); singleton.showMessage(); } }
应用场景
- 数据库连接池。
- 全局配置管理器。
2. 工厂模式
分类
-
简单工厂模式
将对象的创建集中在一个工厂类中。public interface Shape { void draw(); } public class Circle implements Shape { @Override public void draw() { System.out.println("Drawing a circle"); } } public class Rectangle implements Shape { @Override public void draw() { System.out.println("Drawing a rectangle"); } } public class ShapeFactory { public static Shape getShape(String type) { if ("circle".equalsIgnoreCase(type)) { return new Circle(); } else if ("rectangle".equalsIgnoreCase(type)) { return new Rectangle(); } return null; } } // 测试类 public class TestFactory { public static void main(String[] args) { Shape shape1 = ShapeFactory.getShape("circle"); shape1.draw(); Shape shape2 = ShapeFactory.getShape("rectangle"); shape2.draw(); } }
-
工厂方法模式
定义一个创建对象的接口,由子类决定实例化哪个类。public interface Shape { void draw(); } public class Circle implements Shape { @Override public void draw() { System.out.println("Drawing a circle"); } } public abstract class ShapeFactory { public abstract Shape createShape(); } public class CircleFactory extends ShapeFactory { @Override public Shape createShape() { return new Circle(); } } // 测试类 public class TestFactoryMethod { public static void main(String[] args) { ShapeFactory factory = new CircleFactory(); Shape shape = factory.createShape(); shape.draw(); } }
-
抽象工厂模式
提供一个创建一系列相关或依赖对象的接口。public interface Button { void render(); } public interface Checkbox { void render(); } public class WindowsButton implements Button { @Override public void render() { System.out.println("Rendering a Windows button"); } } public class WindowsCheckbox implements Checkbox { @Override public void render() { System.out.println("Rendering a Windows checkbox"); } } public interface GUIFactory { Button createButton(); Checkbox createCheckbox(); } public class WindowsFactory implements GUIFactory { @Override public Button createButton() { return new WindowsButton(); } @Override public Checkbox createCheckbox() { return new WindowsCheckbox(); } } // 测试类 public class TestAbstractFactory { public static void main(String[] args) { GUIFactory factory = new WindowsFactory(); Button button = factory.createButton(); button.render(); Checkbox checkbox = factory.createCheckbox(); checkbox.render(); } }
应用场景
- 动态创建对象(如 UI 组件、数据库驱动)。
3. 建造者模式
定义
将复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
实现方式
public class Computer {
private String cpu;
private String ram;
private String storage;
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.storage = builder.storage;
}
public static class Builder {
private String cpu;
private String ram;
private String storage;
public Builder setCpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder setRam(String ram) {
this.ram = ram;
return this;
}
public Builder setStorage(String storage) {
this.storage = storage;
return this;
}
public Computer build() {
return new Computer(this);
}
}
@Override
public String toString() {
return "Computer{" +
"cpu='" + cpu + '\'' +
", ram='" + ram + '\'' +
", storage='" + storage + '\'' +
'}';
}
}
// 测试类
public class TestBuilder {
public static void main(String[] args) {
Computer computer = new Computer.Builder()
.setCpu("Intel i7")
.setRam("16GB")
.setStorage("512GB SSD")
.build();
System.out.println(computer);
}
}
应用场景
- 构建复杂的对象(如 HTML 文档生成器、游戏角色创建器)。
4. 原型模式
定义
通过复制现有对象来创建新对象,而不是通过 new
创建。
实现方式
import java.util.Objects;
public class Prototype implements Cloneable {
private String data;
public Prototype(String data) {
this.data = data;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Prototype{" +
"data='" + data + '\'' +
'}';
}
}
// 测试类
public class TestPrototype {
public static void main(String[] args) throws CloneNotSupportedException {
Prototype prototype = new Prototype("Original Data");
Prototype clonedPrototype = (Prototype) prototype.clone();
System.out.println("Original: " + prototype);
System.out.println("Cloned: " + clonedPrototype);
clonedPrototype.setData("Modified Data");
System.out.println("After Modification:");
System.out.println("Original: " + prototype);
System.out.println("Cloned: " + clonedPrototype);
}
}
应用场景
- 需要频繁创建相似对象时(如游戏中的敌人克隆)。
二、结构型模式
1. 适配器模式
定义
将一个类的接口转换成客户希望的另一个接口,使原本不兼容的类可以一起工作。
实现方式
-
类适配器(通过继承实现)
public interface Target { void request(); } public class Adaptee { public void specificRequest() { System.out.println("Specific Request"); } } public class Adapter extends Adaptee implements Target { @Override public void request() { specificRequest(); } } // 测试类 public class TestAdapter { public static void main(String[] args) { Target target = new Adapter(); target.request(); } }
-
对象适配器(通过组合实现)
public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void request() { adaptee.specificRequest(); } } // 测试类 public class TestAdapter { public static void main(String[] args) { Adaptee adaptee = new Adaptee(); Target target = new Adapter(adaptee); target.request(); } }
应用场景
- 第三方库与现有系统的集成。
2. 装饰者模式
定义
动态地为对象添加新的功能,而无需修改其原始代码。
实现方式
public interface Component {
void operation();
}
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("Performing base operation");
}
}
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("Adding behavior A");
}
}
// 测试类
public class TestDecorator {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component decoratedComponent = new ConcreteDecoratorA(component);
decoratedComponent.operation();
}
}
应用场景
- 动态扩展功能(如 Java I/O 流中的
BufferedReader
和FileReader
)。
3. 代理模式
定义
为某个对象提供一个代理,以控制对该对象的访问。
实现方式
public interface Service {
void doSomething();
}
public class RealService implements Service {
@Override
public void doSomething() {
System.out.println("Executing real service");
}
}
public class ProxyService implements Service {
private RealService realService;
@Override
public void doSomething() {
if (realService == null) {
realService = new RealService();
}
System.out.println("Proxy: Before calling real service");
realService.doSomething();
System.out.println("Proxy: After calling real service");
}
}
// 测试类
public class TestProxy {
public static void main(String[] args) {
Service proxy = new ProxyService();
proxy.doSomething();
}
}
应用场景
- 远程代理(如 RMI)。
- 虚拟代理(如图片懒加载)。
4. 桥接模式
定义
将抽象部分与实现部分分离,使它们都可以独立变化。
实现方式
public interface Implementor {
void operationImpl();
}
public class ConcreteImplementorA implements Implementor {
@Override
public void operationImpl() {
System.out.println("Concrete Implementor A");
}
}
public abstract class Abstraction {
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
public class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
@Override
public void operation() {
implementor.operationImpl();
}
}
// 测试类
public class TestBridge {
public static void main(String[] args) {
Implementor implementor = new ConcreteImplementorA();
Abstraction abstraction = new RefinedAbstraction(implementor);
abstraction.operation();
}
}
应用场景
- 多维度扩展(如不同形状和颜色的组合)。
三、行为型模式
1. 观察者模式
定义
定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会收到通知并自动更新。
实现方式
import java.util.ArrayList;
import java.util.List;
public interface Observer {
void update(String message);
}
public class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + " received: " + message);
}
}
public class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
// 测试类
public class TestObserver {
public static void main(String[] args) {
Subject subject = new Subject();
Observer observer1 = new ConcreteObserver("Observer 1");
Observer observer2 = new ConcreteObserver("Observer 2");
subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObservers("New Message");
}
}
应用场景
- 订阅/发布系统(如消息队列、事件监听器)。
2. 生产者/消费者模式
定义
通过共享缓冲区实现生产者和消费者的解耦。
实现方式
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class ProducerConsumer {
private Queue<Integer> buffer = new LinkedList<>();
private int capacity = 5;
public synchronized void produce() throws InterruptedException {
while (buffer.size() == capacity) {
wait();
}
int value = new Random().nextInt(100);
buffer.add(value);
System.out.println("Produced: " + value);
notifyAll();
}
public synchronized void consume() throws InterruptedException {
while (buffer.isEmpty()) {
wait();
}
int value = buffer.poll();
System.out.println("Consumed: " + value);
notifyAll();
}
}
// 测试类
public class TestProducerConsumer {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
Thread producerThread = new Thread(() -> {
try {
while (true) {
pc.produce();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumerThread = new Thread(() -> {
try {
while (true) {
pc.consume();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producerThread.start();
consumerThread.start();
}
}
应用场景
- 消息队列。
- 多线程任务调度。
3. 策略模式
定义
定义了一系列算法,并将每个算法封装起来,使它们可以互换。
实现方式
public interface Strategy {
void execute();
}
public class StrategyA implements Strategy {
@Override
public void execute() {
System.out.println("Executing Strategy A");
}
}
public class StrategyB implements Strategy {
@Override
public void execute() {
System.out.println("Executing Strategy B");
}
}
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
// 测试类
public class TestStrategy {
public static void main(String[] args) {
Context context = new Context();
context.setStrategy(new StrategyA());
context.executeStrategy();
context.setStrategy(new StrategyB());
context.executeStrategy();
}
}
应用场景
- 支付方式选择(如支付宝、微信支付)。
4. 模板方法模式
定义
定义一个操作中的算法骨架,而将一些步骤延迟到子类中。
实现方式
public abstract class Game {
public final void play() {
initialize();
startPlay();
endPlay();
}
protected abstract void initialize();
protected abstract void startPlay();
protected abstract void endPlay();
}
public class Football extends Game {
@Override
protected void initialize() {
System.out.println("Football Game Initialized!");
}
@Override
protected void startPlay() {
System.out.println("Football Game Started!");
}
@Override
protected void endPlay() {
System.out.println("Football Game Finished!");
}
}
// 测试类
public class TestTemplateMethod {
public static void main(String[] args) {
Game game = new Football();
game.play();
}
}
应用场景
- 固定流程的业务逻辑(如游戏开发、报表生成)。
5. 状态模式
定义
允许对象在其内部状态改变时改变其行为。
实现方式
public interface State {
void handle();
}
public class ConcreteStateA implements State {
@Override
public void handle() {
System.out.println("Handling state A");
}
}
public class ConcreteStateB implements State {
@Override
public void handle() {
System.out.println("Handling state B");
}
}
public class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public void request() {
state.handle();
}
}
// 测试类
public class TestState {
public static void main(String[] args) {
Context context = new Context();
context.setState(new ConcreteStateA());
context.request();
context.setState(new ConcreteStateB());
context.request();
}
}
应用场景
- 不同状态下执行不同逻辑(如订单状态管理)。