常见的几种设计模式(详细)——应用场景和实现方式

文章目录

  • 单例模式
    • 应用
    • 实现
  • 工厂模式
    • 应用
    • 实现
  • ❓策略模式
    • 应用
    • 实现
  • ‍⚖️代理模式
    • 应用
    • 实现
  • 观察者模式(发布订阅模式)
    • 应用
    • 实现
  • 装饰器模式
    • 应用
    • 实现
  • 模版方法模式
    • 应用
    • 实现
  • ⛓️责任链模式
    • 应用
    • 实现

单例模式

整个程序运行过程中,类只有一个实例,减少内存消耗

应用

  1. 资源管理:需要共享的资源如数据库连接池线程池等,确保只有一个实例管理这些资源
  2. 全局配置:配置类
  3. 日志记录器:在多线程或分布式环境中确保日志记录器唯一性

实现

实现时注意:

  1. 构造器私有化,防止篡改
  2. 只暴露一个公共的获取实例的方法
  3. 是否线程安全
  1. 饿汉式:线程安全,类加载的时候就实例化

    public class Singleton{
        private static final Singleton instance = new Singleton();
        private Singleton(){}
        
        public static Singleton getInstance(){
            return instance;
        }
    }
    
  2. 懒汉式:线程不安全,使用到时再实例化

    public class Singleton{
        private static Singleton instance ;
        private Singleton(){}
        
        public static Singleton getInstance(){
            if(instance == null){
                instance = new Singleton();
            }
            return instance;
        }
    }
    
  3. 双重检查锁:懒汉式的优化,线程安全(使用volatile防止指令重排序)

    public class Singleton{
        private static volatile Singleton instance; //使用volatile防止指针重排序
        private Singleton(){}
        
        public static Singleton getInstance(){
            if(instance == null){  //第一次检查
                synchronized(Singleton.class){
                    if(instance == null){  //第二次检查,保证线程安全
                        instance = new Singleton();
                    }
                }
            }
        }
    }
    
  4. 静态内部类:利用类加载机制实现懒加载和线程安全

    public class Singleton {
        private Singleton() {}
    
        private static class Holder {
            private static final Singleton INSTANCE = new Singleton();
        }
    
        public static Singleton getInstance() {
            return Holder.INSTANCE;
        }
    }
    
    
  5. 枚举单例:简单且防止反射和序列化攻击

    public enum Singleton{
        INSTANCE;
    }
    
    Singleton instance = Singleton.INSTANCE;
    

防止反射入侵:在构造器中添加一个判断,如果对象存在,则抛出异常

序列化和反序列化安全:添加一个readResolve()方法,在进行反序列化时会执行readResolve()方法,确保只有一个实例存在

工厂模式

封装对象的创建逻辑,减低耦合

应用

动态创建不同类型的对象

实现

产品接口、产品实现类、工厂类

// 产品接口
public interface Product {
    void use();
}

// 具体产品A
public class ConcreteProductA implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProductA");
    }
}

// 具体产品B
public class ConcreteProductB implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProductB");
    }
}

// 简单工厂类
public class SimpleFactory {
    public static Product createProduct(String type) {
        switch (type) {
            case "A":
                return new ConcreteProductA();
            case "B":
                return new ConcreteProductB();
            default:
                throw new IllegalArgumentException("Unknown product type");
        }
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Product productA = SimpleFactory.createProduct("A");
        productA.use(); // Output: Using ConcreteProductA

        Product productB = SimpleFactory.createProduct("B");
        productB.use(); // Output: Using ConcreteProductB
    }
}


❓策略模式

封装不同的算法,允许运行时选择不同的策略

应用

同一个业务使用不同的策略

  1. 支付系统
  2. 数据压缩
  3. 日志策略

实现

策略接口、策略实现类(不同策略)、上下文类

// 策略接口
interface Strategy {
    void execute();
}

// 具体策略A
class ConcreteStrategyA implements Strategy {
    @Override
    public void execute() {
        System.out.println("Executing Strategy A");
    }
}

// 具体策略B
class ConcreteStrategyB implements Strategy {
    @Override
    public void execute() {
        System.out.println("Executing Strategy B");
    }
}

// 上下文类
class Context {
    private Strategy strategy;

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void executeStrategy() {
        if (strategy != null) {
            strategy.execute();
        } else {
            System.out.println("No strategy set");
        }
    }
}

// 客户端
public class Main {
    public static void main(String[] args) {
        Context context = new Context();

        Strategy strategyA = new ConcreteStrategyA();
        Strategy strategyB = new ConcreteStrategyB();

        context.setStrategy(strategyA);
        context.executeStrategy(); // Output: Executing Strategy A

        context.setStrategy(strategyB);
        context.executeStrategy(); // Output: Executing Strategy B
    }
}

‍⚖️代理模式

代理对象控制对目标对象的访问

应用

在不修改原来代码的基础上,实现对目标对象的控制和管理

  1. 权限验证
  2. 性能优化:通过代理实现缓存或延迟加载以提高系统性能
  3. 远程访问:客户端访问远程对象时,通过代理封装远程调用细节
  4. 日志记录:在方法调用时添加日志记录功能

实现

接口、实现类、代理类(静态代理)

public interface Subject{
    void request();
}

public RealSubject implements Subject{
    @Override
    public void request(){
        System.out.println("RealSubject request");
    }
}

public class Proxy implements Subject{
    private RealSubject realSubject;
    
    @Override
    public void request(){
        if(realSubject == null)
            realSubject = new RealSubject();
        
        System.out.println("before");
        realSubject.request();
        System.out.println("after");
    }
}

public class Main{
    public static void main(String[] args){
        Subject proxy = new Proxy();
        proxy.request();
    }
}

观察者模式(发布订阅模式)

一个对象状态变化时,依赖它的对象会收到通知

应用

  1. 事件驱动系统:用户操作界面,通过监听事件触发响应
  2. 系统间通信:某个模块发生变化,通知多个依赖模块
  3. 订阅:数据更新,通知所有订阅者(推送通知)

实现

观察者接口、被观察者接口、观察者类、被观察者类

// 观察者接口
interface Observer {
    void update(String message);
}

// 被观察者接口
interface Subject {
    void addObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

// 具体被观察者
class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String state;

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(state);
        }
    }

    public void setState(String state) {
        this.state = state;
        notifyObservers();
    }
}

// 具体观察者
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 update: " + message);
    }
}

// 客户端
public class Main {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();

        Observer observer1 = new ConcreteObserver("Observer1");
        Observer observer2 = new ConcreteObserver("Observer2");

        subject.addObserver(observer1);
        subject.addObserver(observer2);

        subject.setState("New State 1");
        subject.setState("New State 2");
    }
}

装饰器模式

不改变原始类,在其基础上动态扩展功能

应用

  1. 动态扩展功能:对现有对象添加功能,但不希望通过继承方式
  2. 不同功能的组合
  3. 透明扩展:客户端无需了解对象是否被装饰过

实现

组件接口、具体组件实现类、装饰器抽象类、具体装饰器

// 组件接口
interface Component {
    void operation();
}

// 具体组件
class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("ConcreteComponent operation");
    }
}

// 装饰器抽象类
abstract class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
    }
}

// 具体装饰器A
class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        System.out.println("ConcreteDecoratorA added behavior");
    }
}

// 具体装饰器B
class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        System.out.println("ConcreteDecoratorB added behavior");
    }
}

// 客户端
public class Main {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        Component decoratorA = new ConcreteDecoratorA(component);
        Component decoratorB = new ConcreteDecoratorB(decoratorA);

        decoratorB.operation();
        // Output:
        // ConcreteComponent operation
        // ConcreteDecoratorA added behavior
        // ConcreteDecoratorB added behavior
    }
}

模版方法模式

定义一个逻辑框架,把具体的实现留给子类

应用

  1. 定义算法骨架
  2. 复用公共逻辑

例:抽象类、继承抽象类

​ 不同支付渠道的流程都是一样的,包括:前置的参数检查、核心支付逻辑、后置的检查等,可以抽象成一个模版方法(抽象类),不同支付渠道的实现类继承它,并实现支付逻辑。

实现

抽象类、继承抽象类

// 抽象类
abstract class DataProcessor {
    // 模板方法
    public final void process() {
        readData();
        processData();
        writeData();
    }

    protected abstract void readData(); // 读取数据
    protected abstract void processData(); // 处理数据

    protected void writeData() { // 写入数据
        System.out.println("Writing data to output.");
    }
}

// 具体实现类A
class CSVDataProcessor extends DataProcessor {
    @Override
    protected void readData() {
        System.out.println("Reading data from CSV file.");
    }

    @Override
    protected void processData() {
        System.out.println("Processing CSV data.");
    }
}

// 具体实现类B
class JSONDataProcessor extends DataProcessor {
    @Override
    protected void readData() {
        System.out.println("Reading data from JSON file.");
    }

    @Override
    protected void processData() {
        System.out.println("Processing JSON data.");
    }
}

// 客户端
public class Main {
    public static void main(String[] args) {
        DataProcessor csvProcessor = new CSVDataProcessor();
        csvProcessor.process();

        DataProcessor jsonProcessor = new JSONDataProcessor();
        jsonProcessor.process();
    }
}

⛓️责任链模式

将多个对象连接成一条链,沿着这条链传递请求,让每个对象都有机会处理请求,请求会顺着链传递,直到某个对象可以处理。

应用

不同级别处理

  1. 审批流程
  2. 日志系统(不同级别的日志记录)

实现

抽象类、继承抽象类

// 处理器接口
abstract class Handler {
    protected Handler nextHandler;

    public void setNextHandler(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }

    public abstract void handleRequest(String request);
}

// 具体处理器A
class ConcreteHandlerA extends Handler {
    @Override
    public void handleRequest(String request) {
        if ("A".equals(request)) {
            System.out.println("ConcreteHandlerA handled request: " + request);
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        } else {
            System.out.println("No handler for request: " + request);
        }
    }
}

// 具体处理器B
class ConcreteHandlerB extends Handler {
    @Override
    public void handleRequest(String request) {
        if ("B".equals(request)) {
            System.out.println("ConcreteHandlerB handled request: " + request);
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        } else {
            System.out.println("No handler for request: " + request);
        }
    }
}

// 客户端
public class Main {
    public static void main(String[] args) {
        Handler handlerA = new ConcreteHandlerA();
        Handler handlerB = new ConcreteHandlerB();

        handlerA.setNextHandler(handlerB);

        handlerA.handleRequest("A"); // Output: ConcreteHandlerA handled request: A
        handlerA.handleRequest("B"); // Output: ConcreteHandlerB handled request: B
        handlerA.handleRequest("C"); // Output: No handler for request: C
    }
}

你可能感兴趣的:(设计模式,单例模式,观察者模式,工厂方法模式,装饰器模式,策略模式,责任链模式)