一句话概括:把Color抽象出来并作为Shape的一个属性,在Shape初始化的时候确定它是值。
将抽象部分与它的实现部分分离,使他们都可以独立变化。
桥接模式将继承关系转化成关联关系,它降低了类与类之间的耦合度,减少了系统中类的数量,也减少了代码量。
public interface Color{
void applyColor();
}
public abstract class Shape{
//桥接
//Composition - implementor
protected Color color;
//constructor with implementor as input argument
public Shape(Color c){
this.color = c;
}
abstract public void applyColor();
}
The implementation of Shape
public class Triangle extends Shape{
public Triangle(Color c){
super(c);
}
@Override
public void applyColor(){
System.out.print("Triangle filled with color ");
this.color.applyColor();
}
}
public class Pentagon extends Shape{
public Pentagon(Color c) {
super(c);
}
@Override
public void applyColor() {
System.out.print("Pentagon filled with color ");
color.applyColor();
}
}
The implementation of Color
public class RedColor implements Color{
public void applyColor(){
System.out.println("red");
}
}
public class GreenColor implements Color{
public void applyColor(){
System.out.println("green");
}
}
Lets test our bridge pattern implementation with a test program
public class BridgePatternTest{
public static void main(String[] args){
Shape tri = new Triangle(new RedColor());
tri.applyColor();
Shape pent = new Pentagon(new GreenClor());
tri.applyColor();
}
}
The output of above bridge pattern test progran.
Triangle filled with color red.
Pentagon filled with color green.