【設計模式】橋接模式
阿新 • • 發佈:2018-12-10
橋接模式:抽象部分與實現部分分離,使他們可以獨立變化
模型圖
程式碼
public abstract class Abstraction {
@SuppressWarnings("unused")
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor=implementor;
}
abstract void operation();
}
public class RefinedAbstraction extends Abstraction { public RefinedAbstraction(Implementor implementor) { super(implementor); } @Override void operation() { implementor.operation(); } }
public abstract class Implementor {
public abstract void operation();
}
public class ConcreteImplementorA extends Implementor{
@Override
public void operation() {
System.out.println(" ConcreteImplementorA ");
}
}
public class ConcreteImplementorB extends Implementor { @Override public void operation() { System.out.println("ConcreteImplementorB"); } }
public class Test {
public static void main(String[] args) {
Implementor implementor=new ConcreteImplementorA();
Abstraction abstraction=new RefinedAbstraction(implementor);
abstraction.operation();
}
}
案例
需求 有兩款不同的手機A,B。為他們裝配不同的兩個功能功能A與功能B,怎麼樣讓這兩個功能可以獨立的裝配到兩種不同的機型呢,這個時候我們就可以利用橋接模式
如上圖所示,很是形象一座橋,有兩個橋墩。
程式碼
public abstract class Function {
public abstract void display();
}
public class FunctionA extends Function{
@Override
public void display() {
System.out.print("FunctionA ");
}
}
public class FunctionB extends Function {
@Override
public void display() {
System.out.print("FunctionB");
}
}
public abstract class Phone {
protected Function phone_a;
protected Function phone_b;
public Phone(Function phone_a,Function phone_b) {
this.phone_a=phone_a;
this.phone_b=phone_b;
}
public abstract void display();
}
public class PhoneA extends Phone{
public PhoneA(Function phone_a, Function phone_b) {
super(phone_a, phone_b);
}
@Override
public void display() {
phone_a.display();
phone_b.display();
}
}
public class PhoneB extends Phone {
public PhoneB(Function phone_a, Function phone_b) {
super(phone_a, phone_b);
// TODO Auto-generated constructor stub
}
@Override
public void display() {
phone_a.display();
phone_b.display();
}
}
public class TestCls {
public static void main(String[] args) {
Function phone_a=new FunctionA();
Function phone_b=new FunctionB();
Phone phoneA=new PhoneA(phone_a,phone_b);
Phone phoneB=new PhoneB(phone_a,phone_b);
phoneA.display();
System.out.println();
phoneB.display();
}
}
總結
1 如上圖所示 聚合是一種弱引用A包含B B不是A的一部分。如果沒有B那麼A一樣可以獨立存在。組合是一種強引用關係,A包含B B是A的一部分。如果沒有B,那麼A就不是完整的。
2 類似於策略模式而策略模式是相對於一個主題方案而言,談多個不同的解決方案的。對於橋接模式則是針對不同的主題,不通的解決方案。或者不同的分類要獨立控制各自的變化而言的。