《大話設(shè)計模式》閱讀筆記和總結(jié)而钞。原書是C#編寫的,本人用Java實現(xiàn)了一遍拘荡,包括每種設(shè)計模式的UML圖實現(xiàn)和示例代碼實現(xiàn)臼节。
目錄:設(shè)計模式
Github地址:DesignPattern
說明
定義:橋接模式(Bridge),將抽象部分與它的實現(xiàn)部分分離珊皿,使它們都可以獨立地變化网缝。
UML圖:
橋接模式UML圖.png
代碼實現(xiàn):
Implementor類
abstract class Implementor{
public abstract void Operation();
}
ConcreteImplementorA和ConcreteImplementorB等派生類
class ConcreteImplementorA extends Implementor{
@Override
public void Operation() {
System.out.println("具體實現(xiàn)A的方法執(zhí)行");
}
}
class ConcreteImplementorB extends Implementor{
@Override
public void Operation() {
System.out.println("具體實現(xiàn)B的方法執(zhí)行");
}
}
Abstraction類
class Abstraction{
protected Implementor implementor;
public void setImplementor(Implementor implementor) {
this.implementor = implementor;
}
public void Operation(){
implementor.Operation();
}
}
RefinedAbstraction類
class RefinedAbstraction extends Abstraction{
@Override
public void Operation() {
implementor.Operation();
}
}
客戶端代碼
public class BridgePattern {
public static void main(String[] args){
Abstraction ab = new RefinedAbstraction();
ab.setImplementor(new ConcreteImplementorA());
ab.Operation();
ab.setImplementor(new ConcreteImplementorB());
ab.Operation();
}
}
運行結(jié)果
具體實現(xiàn)A的方法執(zhí)行
具體實現(xiàn)B的方法執(zhí)行
示例
例子:我們原來用的手機(jī)都是分為不同的品牌,每種手機(jī)里面都內(nèi)置了很多小游戲蟋定,同時也有很多軟件粉臊,但是不同手機(jī)之間的游戲是不能互相移植的。用程序模擬這個情景驶兜。
UML圖:
橋接模式示例UML圖.png
代碼實現(xiàn):
手機(jī)品牌類
public abstract class HandsetBrand {
protected HandsetSoft soft;
public void setSoft(HandsetSoft soft) {
this.soft = soft;
}
//運行
public abstract void Run();
}
手機(jī)品牌M
public class HandsetBrandM extends HandsetBrand {
@Override
public void Run() {
soft.Run();
}
}
手機(jī)品牌N
public class HandsetBrandN extends HandsetBrand {
@Override
public void Run() {
soft.Run();
}
}
手機(jī)軟件
public abstract class HandsetSoft {
public abstract void Run();
}
游戲扼仲、通訊錄等具體類
手機(jī)游戲
public class HandsetGame extends HandsetSoft {
@Override
public void Run() {
System.out.println("運行手機(jī)游戲");
}
}
手機(jī)通訊錄
public class HandsetAddressList extends HandsetSoft {
@Override
public void Run() {
System.out.println("運行手機(jī)通訊錄");
}
}
客戶端代碼
public class Main {
public static void main(String[] args){
HandsetBrand ab;
ab = new HandsetBrandN();
ab.setSoft(new HandsetGame());
ab.Run();
ab.setSoft(new HandsetAddressList());
ab.Run();
ab = new HandsetBrandM();
ab.setSoft(new HandsetGame());
ab.Run();
ab.setSoft(new HandsetAddressList());
ab.Run();
}
}
運行結(jié)果
運行手機(jī)游戲
運行手機(jī)通訊錄
運行手機(jī)游戲
運行手機(jī)通訊錄