桥接模式(Bridge)定义:将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。
如上图所示,平直的那条"聚合关系"就像一座桥一样。
实现部分:
1 public interface Implementor { 2 public void OperationImpl(); 3 } 4 5 public class ConcreteImplementorA implements Implementor { 6 @Override 7 public void OperationImpl() { 8 // TODO Auto-generated method stub 9 System.out.println("形状:方形"); 10 } 11 } 12 13 public class ConcreteImplementorB implements Implementor { 14 @Override 15 public void OperationImpl() { 16 // TODO Auto-generated method stub 17 System.out.println("形状:圆形"); 18 } 19 }
抽象部分:
1 public abstract class Abstraction { 2 protected Implementor implementor; 3 4 protected Abstraction(Implementor implementor) { 5 this.implementor = implementor; 6 } 7 8 public abstract void Operation(); 9 } 10 11 public class RefinedAbstractionA extends Abstraction { 12 protected RefinedAbstractionA(Implementor implementor) { 13 super(implementor); 14 // TODO Auto-generated constructor stub 15 } 16 17 @Override 18 public void Operation() { 19 // TODO Auto-generated method stub 20 System.out.println("颜色:红色"); 21 implementor.OperationImpl(); 22 } 23 } 24 25 public class RefinedAbstractionB extends Abstraction { 26 protected RefinedAbstractionB(Implementor implementor) { 27 super(implementor); 28 // TODO Auto-generated constructor stub 29 } 30 31 @Override 32 public void Operation() { 33 // TODO Auto-generated method stub 34 System.out.println("颜色:黄色"); 35 implementor.OperationImpl(); 36 } 37 } 38 39 public class RefinedAbstractionC extends Abstraction { 40 protected RefinedAbstractionC(Implementor implementor) { 41 super(implementor); 42 // TODO Auto-generated constructor stub 43 } 44 45 @Override 46 public void Operation() { 47 // TODO Auto-generated method stub 48 System.out.println("颜色:蓝色"); 49 implementor.OperationImpl(); 50 } 51 }
调用方式:
1 public class Client { 2 public static void main(String[] args) { 3 //以这两个抽象类型(接口)声明的对象,是稳定的。根据其子类的不同,会有不同的表现。 4 Implementor imple; 5 Abstraction abs; 6 7 //双重扩展点 8 //方形+红色 9 imple = new ConcreteImplementorA();//方形 10 abs = new RefinedAbstractionA(imple);//将"方形"送入"红色" 11 12 ////圆形+蓝色 13 //imple = new ConcreteImplementorB();//圆形 14 //abs = new RefinedAbstractionC(imple);//将"圆形"送入"蓝色" 15 16 abs.Operation(); 17 } 18 }
执行结果: