讀完後的理解,橋接模式是把兩個抽象類別橋接起來,這樣就可以避免一直繼承
假如有兩個抽象類別會員和支付
public abstract class Member {
abstract String getLevel();
}
public class Gold extends Member {
@Override
String getLevel() {
return "金會員";
}
}
public class Silver extends Member {
@Override
String getLevel() {
return "銀會員";
}
}
public abstract class Pay {
protected Member member;
public Pay() {
}
public Pay(Member member) {
this.member = member;
}
public abstract String getPayment();
}
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();
}
}
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();
}
}
@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());
}
金會員現金測試: 金會員 - 現金支付
銀會員現金測試: 銀會員 - 現金支付
金會員信用卡測試: 金會員 - 信用卡支付
銀會員信用卡測試: 銀會員 - 信用卡支付