設計模式之-橋樑模式

2019-11-03     Java架構人生

原文地址:https://dwz.cn/Gi284ZIU

作者:best.lei

  • 橋樑模式:也叫作橋接模式,是個比較簡單的模式,將抽象和實現解耦,使兩者可以獨立地變化(Decouple an abstraction from its implementation so that the two can vary independently)。
  • 橋樑模式的重點在解耦,我們先來看看橋樑模式的通用類圖:

  • Abstraction抽象化角色:它的主要職責是定義出該角色的行為,同時保存一個對實現化角色的引用,該角色一般是抽象類;
  • Implementor實現化角色:它是接口或者抽象類,定義角色必須的行為和屬性;
  • RefinedAbstraction修正抽象化角色:它引用實現化角色對抽象化角色進行修正;
  • ConcreteImplementor具體實現化角色:實現接口或抽象類定義的方法和屬性。
public interface Implementor {
public void doSomething();
public void doAnything();
}
public class ConcreteImplementor implements Implementor{
@Override
public void doSomething() {
// TODO Auto-generated method stub
System.out.println("this is concreteImplementor doSomething");
}
@Override
public void doAnything() {
// TODO Auto-generated method stub
System.out.println("this is concreteImplementor doAnything");
}
}
public abstract class Abstraction {
private Implementor imp;
public Abstraction(Implementor imp){
this.imp = imp;
}
public void request(){
this.imp.doSomething();
}
public Implementor getImplementor(){
return this.imp;
}
}
public class RefinedAbstraction extends Abstraction{
public RefinedAbstraction(Implementor imp) {
super(imp);
// TODO Auto-generated constructor stub
}
@Override
public void request(){
/**
* 業務處理
*/
super.request();
super.getImplementor().doAnything();
}
}
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Abstraction abs = new RefinedAbstraction(new ConcreteImplementor());
abs.request();
}
}

橋樑模式的優點

  • 抽象和實現分離:為了解決繼承的缺點而提出的設計模式,該模式下,實現可以不受抽象的約束,不用再綁定在一個固定的抽象層次上。
  • 優秀的擴充能力
  • 實現細節對客戶透明,客戶不用關係細節的實現,它已經由抽象層通過聚合關係完成了封裝。
文章來源: https://twgreatdaily.com/zh/TEWML24BMH2_cNUg28R5.html