天天看點

橋接模式

定義:如果某個類存在兩個獨立變化的次元,可以運用橋接模式将這兩個次元分離出來,使兩者可以獨立擴充。與多層繼承方案不同,它将兩個獨立變化的次元設計為兩個獨立的繼承等級結構,并且在抽象層建立一個抽象關聯,該關聯關系就像一條橋一樣

優點:1.分離抽象接口及其實作部分。提高了比繼承更好的解決方案。

           2.子類的數目減少了。

           3.橋接模式提高了系統的可擴充性,在兩個變化次元中任意擴充一個次元,都不需要修改原有系統。

缺點:1.提高了系統的複雜度。

使用場景:1.一個類需要在兩個以上次元擴充,采用繼承方式會導緻子類數量過多

                  例.如果一個類在兩個次元分别有m和n種變化,采用繼承的方式就需要擴充出m*n個子類,且一個次元每增加一種變化就多出另一個次元變化總數的子類;如果将兩個次元拆分再組合,加起來也隻有m+n個子類,且每個次元獨立擴充,一個次元增加一種變化隻需要增加1個子類。

對比圖:原

橋接模式
橋接模式:
橋接模式
類圖:
橋接模式

通用代碼:

第一個次元接口

1. public interface Implementor {
2. void operationImpl();
3. }      

第一個次元實作

1. public class ConcreteImplementor implements Implementor {
2. public void operationImpl() {
3. //todo
4.     }
5. }      

第二個次元(為抽象類,将第一個次元注入)

1. public abstract class Abstraction {
2. protected Implementor impl; //實作類接口
3. 
4. public void setImpl(Implementor impl){
5. this.impl = impl;
6.     }
7. 
8. public abstract void operation();  //聲明抽象業務方法
9. }      

第二個次元的實作

1. public class RefinedAbstraction extends Abstraction {
2.     public void operation() {
3. //todo
4.         impl.operationImpl();
5. //todo
6.     }
7. }      

栗子

1. public interface BallType{
2. 
3. public void ballType();
4. 
5. }      

實作

1. public class Basketball implements BallType{
2. 
3. public void ballType(String color){
4.    system.out.print(color+"的籃球")
5. }
6. 
7. }      
1. public class Football implements BallType{
2. 
3. public void ballType(String color){
4.    system.out.print(color+"的足球")
5. }
6. 
7. }      
1. public class Volleyball implements BallType{
2. 
3. public void ballType(String color){
4.    system.out.print(color+"的排球")
5. }
6. 
7. }      

第二個次元的抽象類

1. public abstract class Color{
2.     BallType ballType;
3. 
4. public void setBallType(BallType ballType) {
5. this.ballType = ballType;
6.     }
7. 
8. public abstract void color();
9. }      
1. public class Red extends Color{
2. 
3.     public void color() {
4.         ballType.ballType("紅色");
5.     }
6. }      

調用

1. public class Client {
2. public static void main(String[] args) {
3.         /足球
4. BallType type = new Football();
5. //紅色
6. Red red = new Red();
7. //紅色足球
8.         red.setBallType(type);
9.         red.color();
10. 
11.     }
12. }      

繼續閱讀