Java设计模式 十四 行为型模式 (Behavioral Patterns)

行为型模式 (Behavioral Patterns)

行为型设计模式 关注于对象之间的通信和职责分配,主要用来优化对象之间的交互提高系统的灵活性。这些模式帮助我们在程序中实现对象之间的责任链、请求传递、行为协作等。行为型模式通常描述了对象之间如何通过消息传递来完成某项任务。

以下是一些常见的行为型设计模式


1. 策略模式 (Strategy Pattern)

策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互换。策略模式使得算法的变化独立于使用算法的客户端。

  • 意图: 定义一系列算法,将每个算法封装成一个类,且使它们可以互换。
  • 应用场景: 需要在多个算法之间进行选择,或者某个类的行为需要在运行时动态切换。

示例:

java 复制代码
// 策略接口
public interface Strategy {
    void execute();
}

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

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

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

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void executeStrategy() {
        strategy.execute();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Strategy strategyA = new ConcreteStrategyA();
        Strategy strategyB = new ConcreteStrategyB();
        
        Context context = new Context(strategyA);
        context.executeStrategy();  // 输出 Strategy A
        
        context = new Context(strategyB);
        context.executeStrategy();  // 输出 Strategy B
    }
}

2. 观察者模式 (Observer Pattern)

观察者模式定义了一种一对多的依赖关系,当一个对象状态发生变化时,所有依赖于它的对象都会得到通知并自动更新。通常用于事件处理系统或订阅/发布模式。

  • 意图: 当一个对象的状态变化时,自动通知并更新所有依赖于它的对象。
  • 应用场景: 当一个对象的变化需要影响其他对象,且不知道有多少对象需要被更新时。

示例:

java 复制代码
// 观察者接口
public interface Observer {
    void update(String message);
}

// 具体观察者1
public class ConcreteObserverA implements Observer {
    @Override
    public void update(String message) {
        System.out.println("Observer A received message: " + message);
    }
}

// 具体观察者2
public class ConcreteObserverB implements Observer {
    @Override
    public void update(String message) {
        System.out.println("Observer B received message: " + message);
    }
}

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

// 具体被观察者
public 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();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();
        Observer observerA = new ConcreteObserverA();
        Observer observerB = new ConcreteObserverB();
        
        subject.addObserver(observerA);
        subject.addObserver(observerB);
        
        subject.setState("New State");  // Observer A and B will be notified
    }
}

3. 责任链模式 (Chain of Responsibility Pattern)

责任链模式通过将请求传递给链中的每个对象,直到有对象处理它。责任链模式让多个对象有机会处理请求,从而避免了请求发送者与接受者之间的耦合。

  • 意图: 让多个对象都有机会处理请求,将请求的处理责任链式传递下去,直到某个对象处理它。
  • 应用场景: 需要将请求分配给多个处理者时,或者某个请求由多个处理者依次处理的场景。

示例:

java 复制代码
// 处理者抽象类
public abstract class Handler {
    protected Handler nextHandler;

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

    public abstract void handleRequest(String request);
}

// 具体处理者1
public class ConcreteHandlerA extends Handler {
    @Override
    public void handleRequest(String request) {
        if (request.equals("A")) {
            System.out.println("Handler A handles the request");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

// 具体处理者2
public class ConcreteHandlerB extends Handler {
    @Override
    public void handleRequest(String request) {
        if (request.equals("B")) {
            System.out.println("Handler B handles the request");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Handler handlerA = new ConcreteHandlerA();
        Handler handlerB = new ConcreteHandlerB();
        
        handlerA.setNextHandler(handlerB);
        
        handlerA.handleRequest("B");  // Handler B handles the request
    }
}

4. 命令模式 (Command Pattern)

命令模式将请求封装成对象,从而使我们可以将请求的调用者和请求的接收者解耦。命令模式允许用户将请求的执行操作参数化,使得请求者可以异步执行请求、排队请求、记录请求历史等。

  • 意图: 将请求封装成一个对象,使得请求发送者和接收者解耦。
  • 应用场景: 需要将请求的发送者与接收者解耦,或者需要将请求存储、撤销等操作。

示例:

java 复制代码
// 命令接口
public interface Command {
    void execute();
}

// 具体命令1
public class ConcreteCommandA implements Command {
    private Receiver receiver;

    public ConcreteCommandA(Receiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        receiver.action();
    }
}

// 接收者类
public class Receiver {
    public void action() {
        System.out.println("Receiver is performing an action");
    }
}

// 调用者类
public class Invoker {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void invoke() {
        command.execute();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command command = new ConcreteCommandA(receiver);
        Invoker invoker = new Invoker();
        
        invoker.setCommand(command);
        invoker.invoke();  // Output: Receiver is performing an action
    }
}

5. 状态模式 (State Pattern)

状态模式允许一个对象在其内部状态改变时,改变其行为。对象看起来好像修改了其类。状态模式通常用于处理有多个状态、且根据不同状态来执行不同行为的场景。

  • 意图: 允许对象在状态改变时,改变其行为。
  • 应用场景: 对象的行为依赖于其状态,且该状态会在运行时改变。

示例:

java 复制代码
// 状态接口
public interface State {
    void handleRequest();
}

// 具体状态1
public class ConcreteStateA implements State {
    @Override
    public void handleRequest() {
        System.out.println("State A is handling the request");
    }
}

// 具体状态2
public class ConcreteStateB implements State {
    @Override
    public void handleRequest() {
        System.out.println("State B is handling the request");
    }
}

// 上下文类
public class Context {
    private State state;

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

    public void request() {
        state.handleRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Context context = new Context();
        
        State stateA = new ConcreteStateA();
        context.setState(stateA);
        context.request();  // Output: State A is handling the request
        
        State stateB = new ConcreteStateB();
        context.setState(stateB);
        context.request();  // Output: State B is handling the request
    }
}

6. 总结

行为型设计模式主要关注于对象之间的交互和责任分配。

相关推荐
Scott9999HH4 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
腻害兔4 小时前
【若依项目-产品经理视角】深度拆解 RuoYi-Vue-Pro 商城模块:从商品管理到交易引擎,50 张表撑起一整套电商系统
java·大数据·vue.js·产品经理·ai编程
码智社5 小时前
AES加密原理详解及Java实现加解密实战
java·开发语言
AI云海5 小时前
python 列表、元组、集合和字典
开发语言·python
萧瑟余晖6 小时前
JDK 26 新特性详解
java·开发语言
马优晨7 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
人邮异步社区9 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大9 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai10 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
维天说10 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json