天天看點

設計模式之橋接模式(結構型)

@[toc]

模式定義

橋接模式(Bridge Pattern)是将抽象部分和實作部分分離,使它們可以獨立地改變,是一種對象結構型模式。

模式角色

橋接模式包含如下角色:

  • Abstraction(抽象類)
  • RefinedAbstraction(擴充抽象類)
  • Implementor(實作類接口)
  • ConcreteImplementor(具體實作類)

模式分析

橋接模式關鍵在于如何将抽象化與實作化解耦,使得兩者可以獨立改變。

抽象化:抽象就是忽略一些資訊,将不同的實體當作同樣的實體對待。在面向對象中将對象的共同性質抽取出來形成類的過程稱之為抽象化的過程

實作化:針對抽象話給出的具體實作,就是實作化,抽象化與實作化是互逆的過程

解耦:解耦就是将抽象化和實作化直接的耦合解脫開,或者說将兩者之間的強關聯變成弱關聯,将兩個角色由繼承改成關聯關系(組合或者聚合)

典型代碼:

public interface Implementor
{
    public void operationImpl();
}      
public abstract class Abstraction
{
    protected Implementor impl;
    
    public void setImpl(Implementor impl)
    {
        this.impl=impl;
    }
    
    public abstract void operation();
}      
public class RefinedAbstraction extends Abstraction
{
    public void operation()
    {
        //代碼
        impl.operationImpl();
        //代碼
    }
}      

模式例子

畫出不同顔色的圓,DrawAPI 接口的實體類 RedCircle、GreenCircle。Shape 是一個抽象類,例子來自:​​http://www.runoob.com/design-pattern/bridge-pattern.html​​

建立橋接接口:

public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}      

接口具體實作類:

public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}      
public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}      

抽象類關聯方式實作接口:

public abstract class Shape {
   protected DrawAPI drawAPI;
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();  
}      

具體類實作抽象類:

public class Circle extends Shape {
   private int x, y, radius;
 
   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }
 
   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}      
public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
 
      redCircle.draw();
      greenCircle.draw();
   }
}      
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[  color: green, radius: 10, x: 100, 100]      

模式應用

  • 一些軟體的跨平台設計有時候也是應用了橋接模式
  • JDBC的驅動程式,實作了将不同類型的資料庫與Java程式的綁定
  • Java虛拟機實作了平台的無關性,Java虛拟機設計就是通過橋接模式

繼續閱讀