設計模式之橋接模式(結構型)
阿新 • • 發佈:2019-03-09
n) oid 實現接口 div 創建 結構型模式 face interface pre
目錄
- 模式定義
- 模式角色
- 模式分析
- 模式例子
- 模式應用
@
模式定義
橋接模式(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虛擬機設計就是通過橋接模式
設計模式之橋接模式(結構型)