职责链模式(Chain of Responsibility)

2018-12-03  本文已影响8人  fomin

1、概念

职责链模式为为解除请求的发送者和接收者之间耦合,而使多个对象都有机会处理这个请求。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它,属于行为型模式。


未命名文件(6).png

2、模式结构

3、使用场景

4、优缺点

优点:

缺点:

5、实例

定义实体类User

public class User {
    private int userId;
    private String userName;
    private int userPoint;

    public User(int userId, String userName, int userPoint) {
        this.userId = userId;
        this.userName = userName;
        this.userPoint = userPoint;
    }

    public int getUserId() {
        return userId;
    }

    public int getUserPoint() {
        return userPoint;
    }

    public String getUserName() {
        return userName;
    }
}

定义抽象Handler角色LevelHandler

public abstract class LevelHandler {
    protected LevelHandler next;

    public LevelHandler getNext() {
        return next;
    }

    public void setNext(LevelHandler next) {
        this.next = next;
    }

    public abstract void handleAction(User user, int point);
}

定义具体NormalLevel

public class NormalLevel extends LevelHandler {

    private static final int needPoint = 1000;

    @Override
    public void handleAction(User user, int point) {
        if (user.getUserPoint() + point > needPoint) {
            getNext().handleAction(user, point);
        } else {
            // 业务逻辑
        }
    }
}

定义具体AdvancedLevel

public class AdvancedLevel extends LevelHandler {

    private static final int needPoint = 5000;

    @Override
    public void handleAction(User user, int point) {
        if (user.getUserPoint() + point > needPoint) {
            getNext().handleAction(user, point);
        } else {
            // 业务逻辑
        }
    }
}

定义具体VIPLevel

public class VIPLevel extends LevelHandler {

    private static final int needPoint = 10000;

    @Override
    public void handleAction(User user, int point) {
        // 业务逻辑
    }
}

客户端调用

NormalLevel normalLevel = new NormalLevel();
AdvancedLevel advancedLevel = new AdvancedLevel();
VIPLevel vipLevel = new VIPLevel();
normalLevel.setNext(advancedLevel);
advancedLevel.setNext(vipLevel);
normalLevel.handleAction(new User(100, "text", 1000), 1000);
上一篇下一篇

猜你喜欢

热点阅读