设计模式之桥接模式!
发表于更新于
桥接模式就是把抽象和实现分离出来,然后中间通过组合来搭建他们之间的桥梁。
UML类图:

代码实现
中国有很多银行,有中国农业银行和中国工商银行,关于账号,有定期账号和活期账号,一个就是银行一个账号。
1 2 3 4 5 6 7 8
| public interface Account { Account openAccount(); void showAccountType();
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class DepositAccount implements Account { @Override public Account openAccount() { System.out.println("定期账号"); return new DepositAccount(); }
@Override public void showAccountType() { System.out.println("这是一个定期账号"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class SavingAccount implements Account { @Override public Account openAccount() { System.out.println("打开活期账号"); return new SavingAccount(); }
@Override public void showAccountType() { System.out.println("这是一个活期账号"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| public abstract class Bank { protected Account account;
public Bank(Account account) { this.account = account; }
abstract Account openAccount();
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class ABCBank extends Bank {
public ABCBank(Account account) { super(account); }
@Override Account openAccount() { System.out.println("打开中国农业银行账号"); return account; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class ICBCBank extends Bank {
public ICBCBank(Account account) { super(account); }
@Override Account openAccount() { System.out.println("打开中国工商银行账号"); return account; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Test { public static void main(String[]args){ Bank icbcBank = new ICBCBank(new DepositAccount()); Account icbcAccount = icbcBank.openAccount(); icbcAccount.showAccountType();
Bank icbcBank2 = new ICBCBank(new SavingAccount()); Account icbcAccount2 = icbcBank2.openAccount(); icbcAccount2.showAccountType();
Bank abcBank = new ABCBank(new SavingAccount()); Account abcAccount = abcBank.openAccount(); abcAccount.showAccountType(); } }
|