Bridge模式就是将类的功能层次结构和类的实现层次结构连接起来。
1 package bigjunoba.bjtu.function; 2 3 import bigjunoba.bjtu.implement.DisplatImpl; 4 5 public class Display { 6 7 private DisplatImpl impl; 8 9 public Display(DisplatImpl impl) { 10 this.impl = impl; 11 } 12 13 public void open() { 14 impl.rawOpen(); 15 } 16 17 public void pring() { 18 impl.rawPrint(); 19 } 20 21 public void close() { 22 impl.rawClose(); 23 } 24 25 public final void display() { 26 open(); 27 pring(); 28 close(); 29 } 30 }
Display类。
1 package bigjunoba.bjtu.function; 2 3 import bigjunoba.bjtu.implement.DisplatImpl; 4 5 public class CountDisplay extends Display{ 6 7 public CountDisplay(DisplatImpl impl) { 8 super(impl); 9 } 10 11 public void multiDisplay(int times) { 12 open(); 13 for (int i = 0; i < times; i++) { 14 pring(); 15 } 16 close(); 17 } 18 19 }
CountDisplay类。
1 package bigjunoba.bjtu.implement; 2 3 public abstract class DisplatImpl { 4 5 public abstract void rawOpen(); 6 public abstract void rawPrint(); 7 public abstract void rawClose(); 8 9 }
1 package bigjunoba.bjtu.implement; 2 3 public class StringDisplayImpl extends DisplatImpl{ 4 5 private String string; 6 private int width; 7 public StringDisplayImpl(String string) { 8 this.string = string; 9 this.width = string.getBytes().length; 10 } 11 12 @Override 13 public void rawOpen() { 14 printLine(); 15 } 16 17 @Override 18 public void rawPrint() { 19 System.out.println("|" + string + "|"); 20 } 21 22 @Override 23 public void rawClose() { 24 printLine(); 25 } 26 27 private void printLine() { 28 System.out.print("+"); 29 for (int i = 0; i < width; i++) { 30 System.out.print("-"); 31 } 32 System.out.println("+"); 33 } 34 35 }
StringDisplayImpl类。
1 package bigjunoba.bjtu.test; 2 3 import bigjunoba.bjtu.function.CountDisplay; 4 import bigjunoba.bjtu.function.Display; 5 import bigjunoba.bjtu.implement.StringDisplayImpl; 6 7 public class Main { 8 9 public static void main(String[] args) { 10 Display display1 = new Display(new StringDisplayImpl("Lianjiang")); 11 Display display2 = new CountDisplay(new StringDisplayImpl("Lianjiangjiang")); 12 CountDisplay countDisplay = new CountDisplay(new StringDisplayImpl("Lianjiangjiangjiang")); 13 display1.display(); 14 display2.display(); 15 countDisplay.display(); 16 countDisplay.multiDisplay(5); 17 } 18 }
Main类。
+---------+ |Lianjiang| +---------+ +--------------+ |Lianjiangjiang| +--------------+ +-------------------+ |Lianjiangjiangjiang| +-------------------+ +-------------------+ |Lianjiangjiangjiang| |Lianjiangjiangjiang| |Lianjiangjiangjiang| |Lianjiangjiangjiang| |Lianjiangjiangjiang| +-------------------+
输出结果是这样的。