在 Java 开发中,设计模式是解决常见问题的经典方案。以下是 Java 开发中常用的设计模式,结合实际应用场景和代码示例进行说明:

一、创建型模式

1. 单例模式 (Singleton Pattern)

  • 用途:确保一个类只有一个实例,并提供全局访问点。
  • 场景:数据库连接池、线程池、配置管理类。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton {
private static Singleton instance;

private Singleton() {} // 私有构造函数

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

2. 工厂模式 (Factory Pattern)

  • 用途:将对象的创建与使用分离,通过工厂类统一管理对象的创建。
  • 场景:日志记录器、数据库连接工厂。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface Product {
void use();
}

class ConcreteProduct implements Product {
public void use() {
System.out.println("Using ConcreteProduct");
}
}

class ProductFactory {
public static Product createProduct() {
return new ConcreteProduct();
}
}

3. 抽象工厂模式 (Abstract Factory Pattern)

  • 用途:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
  • 场景:构建复杂的对象(如 HTTP 请求、SQL 查询)。
  • 示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Button {
void render();
}

class WindowsButton implements Button {
public void render() {
System.out.println("Render a Windows button");
}
}

interface GUIFactory {
Button createButton();
}

class WindowsFactory implements GUIFactory {
public Button createButton() {
return new WindowsButton();
}
}

4. 建造者模式 (Builder Pattern)

  • 用途:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
  • 场景:构建复杂的对象(如 HTTP 请求、SQL 查询)。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Product {
private String part1;
private String part2;

public void setPart1(String part1) { this.part1 = part1; }
public void setPart2(String part2) { this.part2 = part2; }
}

class Builder {
private Product product = new Product();

public Builder withPart1(String part1) {
product.setPart1(part1);
return this;
}

public Builder withPart2(String part2) {
product.setPart2(part2);
return this;
}

public Product build() {
return product;
}
}

5. 原型模式(Prototype Pattern)

  • 用途:通过复制现有实例创建新实例,而不是通过新建实例,减少实例化开销,提高性能。
  • 场景:需要频繁创建相似对象的场景。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Prototype {
Prototype clone();
}

class ConcretePrototype implements Prototype {
private String field;

public ConcretePrototype(String field) {
this.field = field;
}

public Prototype clone() {
return new ConcretePrototype(this.field);
}

public String getField() {
return field;
}
}

二、结构型模式

1. 适配器模式 (Adapter Pattern)

  • 用途:将一个类的接口转换成客户端期望的另一个接口。
  • 场景:兼容旧系统、第三方库的集成。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface Target {
void request();
}

class Adaptee {
public void specificRequest() {
System.out.println("Adaptee's specific request");
}
}

class Adapter implements Target {
private Adaptee adaptee;

public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}

public void request() {
adaptee.specificRequest();
}
}

2. 代理模式 (Proxy Pattern)

  • 用途:为其他对象提供一个代理,以控制对这个对象的访问。
  • 场景:延迟加载、权限控制、日志记录。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
interface Image {
void display();
}

class RealImage implements Image {
private String filename;

public RealImage(String filename) {
this.filename = filename;
loadFromDisk();
}

private void loadFromDisk() {
System.out.println("Loading " + filename);
}

public void display() {
System.out.println("Displaying " + filename);
}
}

class ProxyImage implements Image {
private RealImage realImage;
private String filename;

public ProxyImage(String filename) {
this.filename = filename;
}

public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}

3. 装饰器模式 (Decorator Pattern)

  • 用途:动态地给对象添加额外的职责,而不改变其结构。
  • 场景:Java I/O 流、Spring 的 AOP。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
interface Coffee {
double getCost();
String getDescription();
}

class SimpleCoffee implements Coffee {
public double getCost() {
return 5;
}

public String getDescription() {
return "Simple Coffee";
}
}

class MilkDecorator implements Coffee {
private Coffee coffee;

public MilkDecorator(Coffee coffee) {
this.coffee = coffee;
}

public double getCost() {
return coffee.getCost() + 2;
}

public String getDescription() {
return coffee.getDescription() + ", Milk";
}
}

三、行为型模式

1. 观察者模式 (Observer Pattern)

  • 用途:定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖它的对象都会收到通知。
  • 场景:事件驱动系统、消息队列。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.ArrayList;
import java.util.List;

interface Observer {
void update(String message);
}

class ConcreteObserver implements Observer {
public void update(String message) {
System.out.println("Received: " + message);
}
}

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);
}
}
}

2. 策略模式 (Strategy Pattern)

  • 用途:定义一系列算法,将每个算法封装起来,并使它们可以互换。
  • 场景:支付方式选择、排序算法。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
interface PaymentStrategy {
void pay(int amount);
}

class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " via Credit Card");
}
}

class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " via PayPal");
}
}

class PaymentContext {
private PaymentStrategy strategy;

public PaymentContext(PaymentStrategy strategy) {
this.strategy = strategy;
}

public void executePayment(int amount) {
strategy.pay(amount);
}
}

3. 模板方法模式 (Template Method Pattern)

  • 用途:定义一个算法的骨架,将一些步骤延迟到子类中实现。
  • 场景:框架设计、流程固定的业务逻辑。
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();

public final void play() {
initialize();
startPlay();
endPlay();
}
}

class Football extends Game {
void initialize() {
System.out.println("Football Game Initialized");
}

void startPlay() {
System.out.println("Football Game Started");
}

void endPlay() {
System.out.println("Football Game Ended");
}
}

四、总结

模式类型 常用模式 典型应用场景
创建型模式 单例、工厂、抽象工厂、建造者 对象创建、资源管理
结构型模式 适配器、代理、装饰器 接口兼容、功能扩展、访问控制
行为型模式 观察者、策略、模板方法 事件处理、算法选择、流程固定化

这些设计模式在Java开发中广泛应用,熟练掌握它们可以显著提高代码质量和开发效率。