iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0
Mobile Development

肯定會斷賽之在 Android 開發使用設計模式系列 第 22

113/22 - 責任鏈模式(Chain of Responsibility)- Java

  • 分享至 

  • xImage
  •  

介紹

讀完後我的理解是他讓兩個繼承的類別有上下級關係,可以做階層的應用

責任鏈模式實作

public class ApplyRequest {

    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
public abstract class Mall {

    protected String name;

    protected Mall superior;

    public Mall(String name) {
        this.name = name;
    }

    public void setSuperior(Mall superior) {
        this.superior = superior;
    }

    public String getName() {
        return name;
    }

    abstract public String apply(ApplyRequest applyRequest);
}
public class FamilyMark extends Mall {

    public FamilyMark(String name) {
        super(name);
    }

    @Override
    public String apply(ApplyRequest applyRequest) {
        String text;
        if ("超商".equals(applyRequest.getType())) {
            text = "這是超商類別,執行";
        } else {
            text = "這不是超商類別,不執行";

            if (null != superior) {
                superior.apply(applyRequest);
            }
        }
        return text;
    }
}
public class Carrefour extends Mall{

    public Carrefour(String name) {
        super(name);
    }

    @Override
    public String apply(ApplyRequest applyRequest) {
        String text;
        if ("商場".equals(applyRequest.getType())) {
            text = "這是商場類別,執行";
        } else {
            text = "這不是商場類別,不執行";

            if (null != superior) {
                superior.apply(applyRequest);
            }
        }
        return text;
    }
}

責任鏈模式測試

public class JavaTest {

    @Test
    public void show() {

        StringBuilder text;
        text = new StringBuilder();
        text.append("\n");

        Mall familyMark = new FamilyMark("全家");
        Mall carrefour = new Carrefour("家樂福");

        text.append("店名:");
        text.append(familyMark.getName());
        familyMark.setSuperior(carrefour);

        text.append("\n");

        ApplyRequest applyRequest = new ApplyRequest();
        applyRequest.setType("超商");
        text.append(familyMark.apply(applyRequest));

        text.append("\n");

        applyRequest.setType("商場");
        text.append(familyMark.apply(applyRequest));

        assertEquals("測試", text.toString());
    }
}

上一篇
113/21 - 策略模式(Strategy)- Kotlin
下一篇
113/23 - 責任鏈模式(Chain of Responsibility)- Kotlin
系列文
肯定會斷賽之在 Android 開發使用設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言