iT邦幫忙

2024 iThome 鐵人賽

DAY 16
0

介紹

讀完後的理解,橋接模式是把兩個抽象類別橋接起來,這樣就可以避免一直繼承

假如有兩個抽象類別會員和支付

  1. 會員(Member)
    1. 金會員(Gold)
    2. 銀會員(Silver)
  2. 支付(Pay)
    1. 現金支付(Cash)
    2. 信用卡支付(CreditCard)

橋接模式實作

  1. 會員
public abstract class Member {
    abstract String getLevel();
}
  1. 金會員
public class Gold extends Member {

    @Override
    String getLevel() {
        return "金會員";
    }
}
  1. 銀會員
public class Silver extends Member {
    
    @Override
    String getLevel() {
        return "銀會員";
    }
}
  1. 支付
public abstract class Pay {

    protected Member member;

    public Pay() {

    }

    public Pay(Member member) {
        this.member = member;
    }

    public abstract String getPayment();
}
  1. 現金支付
public class Cash extends Pay {

    public Cash(Member member) {
        super(member);
    }

    @Override
    public String getPayment() {
        StringBuilder text;
        text = new StringBuilder();
        text.append(super.member.getLevel());
        text.append(" - ");
        text.append("現金支付");
        return text.toString();
    }
}
  1. 信用卡支付
public class CreditCard extends Pay {

    public CreditCard(Member member) {
        super(member);
    }

    @Override
    public String getPayment() {
        StringBuilder text;
        text = new StringBuilder();
        text.append(super.member.getLevel());
        text.append(" - ");
        text.append("信用卡支付");
        return text.toString();
    }
}

橋接模式測試

  1. 測試案例
    @Test
    public void show() {

        StringBuilder text;
        text = new StringBuilder();

        text.append("\n");
        text.append("金會員現金測試: ");
        Pay payCashGold = new Cash(new Gold());
        text.append(payCashGold.getPayment());

        text.append("\n");
        text.append("銀會員現金測試: ");
        Pay payCashSilver = new Cash(new Silver());
        text.append(payCashSilver.getPayment());

        text.append("\n");
        text.append("金會員信用卡測試: ");
        Pay payCreditCardGold = new CreditCard(new Gold());
        text.append(payCreditCardGold.getPayment());

        text.append("\n");
        text.append("銀會員信用卡測試: ");
        Pay payCreditCardSilver = new CreditCard(new Silver());
        text.append(payCreditCardSilver.getPayment());
        text.append("\n");

        assertEquals("測試", text.toString());
    }
  1. 執行測試
金會員現金測試: 金會員 - 現金支付
銀會員現金測試: 銀會員 - 現金支付
金會員信用卡測試: 金會員 - 信用卡支付
銀會員信用卡測試: 銀會員 - 信用卡支付

上一篇
113/15 - 裝飾模式(Decorator)- Kotlin
下一篇
113/17 - 橋接模式(Bridge)- Kotlin
系列文
肯定會斷賽之在 Android 開發使用設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言