设计模式是面向对象编程中一种解决特定问题的通用方案。它并不是直接可以用来复制的代码,而是解决问题的思路和结构框架。在这篇博客中,我们将详细讨论几种常见的设计模式:单例模式、工厂模式(简单工厂、工厂方法、抽象工厂)、策略模式和责任链模式。
1. 单例模式(Singleton Pattern)
定义
单例模式是一种创建型设计模式,旨在确保一个类只有一个实例,并提供一个全局的访问点来获取该实例。
优缺点
-
优点:
-
确保系统中该类只有一个实例。
-
提供全局访问点,便于管理资源。
-
-
缺点:
-
不容易进行单元测试。
-
难以扩展,如果需要增加多个实例就不适用了。
-
典型代码
饿汉式(Eager Singleton):
public class Singleton {
// 类加载时就创建实例
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
懒汉式(Lazy Singleton):
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 class Main {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2); // 输出 true
}
}
2. 工厂模式(Factory Pattern)
工厂模式属于创建型设计模式,主要用于定义一个创建对象的接口,让子类决定实例化哪个类。工厂方法把类的实例化推迟到子类。
简单工厂模式(Simple Factory)
定义
简单工厂模式通过一个工厂类来创建不同类型的对象。工厂类根据传入的参数决定实例化哪一个产品类。
优缺点
-
优点:
-
简化了对象的创建过程。
-
客户端不需要了解对象的创建过程,只需提供输入参数。
-
-
缺点:
- 增加新的产品时,需要修改工厂类,违背了开放-封闭原则。
典型代码
public class Product {
public void show() {
System.out.println("Product created!");
}
}
public class SimpleFactory {
public static Product createProduct() {
return new Product();
}
}
使用代码
public class Main {
public static void main(String[] args) {
Product product = SimpleFactory.createProduct();
product.show();
}
}
工厂方法模式(Factory Method)
定义
工厂方法模式通过定义一个接口来创建对象,由子类来决定实例化哪一个类。与简单工厂不同的是,工厂方法不由工厂类来控制实例化过程。
优缺点
-
优点:
-
增加新产品时,不需要修改已有代码,符合开放-封闭原则。
-
每个具体工厂类负责创建一个具体产品,遵循单一职责原则。
-
-
缺点:
- 如果产品种类较多,工厂类数量也会增加,导致类的数量激增。
典型代码
// 产品接口
public interface Product {
void show();
}
// 具体产品实现
public class ProductA implements Product {
public void show() {
System.out.println("ProductA created!");
}
}
// 工厂接口
public interface Factory {
Product createProduct();
}
// 具体工厂
public class FactoryA implements Factory {
public Product createProduct() {
return new ProductA();
}
}
使用代码
public class Main {
public static void main(String[] args) {
Factory factory = new FactoryA();
Product product = factory.createProduct();
product.show();
}
}
抽象工厂模式(Abstract Factory)
定义
抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而无需明确指定具体类。抽象工厂模式通过创建多个工厂来创建相关对象。
优缺点
-
优点:
-
提供一个接口来创建一系列相关的对象,客户端无需知道具体实现类。
-
增加新的产品系列时,只需要增加具体工厂类即可,符合开放-封闭原则。
-
-
缺点:
- 工厂类会增加,系统复杂度上升。
典型代码
// 产品接口
public interface ProductA {
void showA();
}
public interface ProductB {
void showB();
}
// 具体产品
public class ProductA1 implements ProductA {
public void showA() {
System.out.println("ProductA1 created!");
}
}
public class ProductB1 implements ProductB {
public void showB() {
System.out.println("ProductB1 created!");
}
}
// 抽象工厂
public interface AbstractFactory {
ProductA createProductA();
ProductB createProductB();
}
// 具体工厂
public class ConcreteFactory1 implements AbstractFactory {
public ProductA createProductA() {
return new ProductA1();
}
public ProductB createProductB() {
return new ProductB1();
}
}
使用代码
public class Main {
public static void main(String[] args) {
AbstractFactory factory = new ConcreteFactory1();
ProductA productA = factory.createProductA();
ProductB productB = factory.createProductB();
productA.showA();
productB.showB();
}
}
3. 策略模式(Strategy Pattern)
定义
策略模式是一种行为型设计模式,定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。策略模式让算法的变化独立于使用算法的客户端。
优缺点
-
优点:
-
客户端可以根据需要选择算法,避免了大量的条件判断。
-
新增算法时,客户端不需要修改,只需要新增策略类即可。
-
-
缺点:
- 可能会增加系统中的类数,过多的策略类会导致系统复杂度上升。
典型代码
// 策略接口
public interface Strategy {
void execute();
}
// 具体策略
public class StrategyA implements Strategy {
public void execute() {
System.out.println("Executing StrategyA");
}
}
public class StrategyB implements Strategy {
public void execute() {
System.out.println("Executing StrategyB");
}
}
// 上下文
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
使用代码
public class Main {
public static void main(String[] args) {
Strategy strategyA = new StrategyA();
Context context = new Context(strategyA);
context.executeStrategy(); // 执行 StrategyA
Strategy strategyB = new StrategyB();
context = new Context(strategyB);
context.executeStrategy(); // 执行 StrategyB
}
}
4. 责任链模式(Chain of Responsibility Pattern)
定义
责任链模式是一种行为型设计模式,旨在避免请求发送者与多个请求处理者之间的耦合关系。通过链式传递,能够将请求传递给不同的处理者,直到一个处理者处理该请求。
优缺点
-
优点:
-
请求发送者不需要知道哪个处理者处理了请求,解耦了发送者与处理者。
-
可以动态地增加或删除处理者,符合开放-封闭原则。
-
-
缺点:
-
责任链的处理者如果设置不当,可能导致请求无法得到处理。
-
需要确保责任链中所有处理者的顺序和逻辑。
-
典型代码
// 抽象处理者
public abstract class Handler {
protected Handler nextHandler;
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public abstract void handleRequest(int request);
}
// 具体处理者
public class ConcreteHandlerA extends Handler {
public void handleRequest(int request) {
if (request < 10) {
System.out.println("HandlerA handling request " + request);
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
public class ConcreteHandlerB extends Handler {
public void handleRequest(int request) {
if (request >= 10) {
System.out.println("HandlerB handling request " + request);
} else if (nextHandler != null) {
nextHandler.handleRequest(request);
}
}
}
使用代码
public class Main {
public static void main(String[] args) {
Handler handlerA = new ConcreteHandlerA();
Handler handlerB = new ConcreteHandlerB();
handlerA.setNextHandler(handlerB);
handlerA.handleRequest(5); // HandlerA handling request 5
handlerA.handleRequest(15); // HandlerB handling request 15
}
}