介紹和介紹
橋接模式也成為橋梁模式乍丈,是將抽象部分和實(shí)現(xiàn)部分分離,使他們可以獨(dú)立地進(jìn)行變化把将。
簡(jiǎn)單實(shí)現(xiàn)
- 實(shí)現(xiàn)部分的抽象接口
public interface Implementor {
/**
* 抽象部分的具體方法
*/
void operationImpl();
}
- 實(shí)現(xiàn)部分的具體的實(shí)現(xiàn)A
public class ImplementorA implements Implementor {
@Override
public void operationImpl() {
//具體實(shí)現(xiàn)A
}
}
- 實(shí)現(xiàn)部分具體的實(shí)現(xiàn)B
public class ImplementorB implements Implementor {
@Override
public void operationImpl() {
//具體實(shí)現(xiàn)B
}
}
- 抽象類
public abstract class Abstraction {
Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
//抽象類的功能
public void operation(){
implementor.operationImpl();
}
}
- 抽象類子類
public class RefinedAbstration extends Abstraction {
public RefinedAbstration(Implementor implementor) {
super(implementor);
}
/**
* 對(duì)父類方法的擴(kuò)展
*/
public void refinedOperation(){
}
}
實(shí)例
現(xiàn)在有四種咖啡轻专, 大杯加糖,大杯原味察蹲,小杯不加糖请垛,小杯原味。本質(zhì)上講洽议,一共有兩種變化宗收,大小杯+是否加糖。
- 首先定義一個(gè)抽象類表示咖啡內(nèi)添加物
public abstract class CoffeeAdditives {
/**
* 由子類決定添加何種添加物
* @return
*/
abstract String add();
}
-
集成抽象類亚兄,實(shí)現(xiàn)具體方法
- 原味
public class Ordinary extends CoffeeAdditives { @Override String add() { return "原味"; } }
- 加糖
public class Sugar extends CoffeeAdditives { @Override String add() { return "加糖"; } }
定義一個(gè)咖啡類
public abstract class Coffee {
protected CoffeeAdditives coffeeAdditives;
public Coffee(CoffeeAdditives coffeeAdditives) {
this.coffeeAdditives = coffeeAdditives;
}
/**
* 具體制作過程由子類決定
*/
public abstract void makeCoffee();
}
-
定義兩個(gè)子類
- 大杯
public class LargeCoffee extends Coffee{ public LargeCoffee(CoffeeAdditives coffeeAdditives) { super(coffeeAdditives); } @Override public void makeCoffee() { //大杯制作混稽,并由 coffeeAdditives 決定加料 } }
- 小杯
public class SmallCoffee extends Coffee{ public LargeCoffee(CoffeeAdditives coffeeAdditives) { super(coffeeAdditives); } @Override public void makeCoffee() { //小杯制作,并由 coffeeAdditives 決定加料 } }
客戶端類
public class Main {
public static void main(String[] args) {
Ordinary ordinary = new Ordinary();
Sugar sugar = new Sugar();
LargeCoffee largeCoffee1 = new LargeCoffee(ordinary);
LargeCoffee largeCoffee2 = new LargeCoffee(sugar);
SmallCoffee smallCoffee1 = new SmallCoffee(ordinary);
SmallCoffee smallCoffee2 = new SmallCoffee(sugar);
}
}
這樣一個(gè)簡(jiǎn)單的橋接模式應(yīng)用就完成了审胚。如果再增加一種中杯咖啡匈勋,只要再擴(kuò)展一個(gè) MiddleCoffee 子類就可以了。
使用場(chǎng)景
多維度變化類或者說多個(gè)樹狀類之間的耦合就可以使用橋接模式來實(shí)現(xiàn)解耦膳叨。