设计模式之桥接模式(Bridge)简单实例

来源:互联网 发布:linux top命令进程状态 编辑:程序博客网 时间:2024/05/21 07:03

桥接模式

1桥接模式就是适配器模式的变种,把另外一个类也变成了接口或抽象类,让他更加动态,其实设计模式的最终目的就是为了让代码改动量更小的前提下完成要扩展的业务,方便维护。就是个加强版的适配器模式。原理没有太大差别,也不算难

2 具体实现类

/** *  * @author chaigw * */public class BridgeDesign {public static void main(String[] args) {BridgeDesign bridge = new BridgeDesign();GradeOne one= bridge.new GradeOne("smart");one.getGradeName();GradeTwo two= bridge.new GradeTwo("smart");two.getGradeName();System.out.println("-------------->");GradeOne one2= bridge.new GradeOne("stupid");one2.getGradeName();GradeTwo two2= bridge.new GradeTwo("stupid");two2.getGradeName();}class GradeOne extends Grade{private String gradeName = "一班的";Student student = null;public GradeOne(String type) {this.student = getStudent(type);}public void getGradeName(){System.out.println("小明是"+gradeName);student.getStudentType();}}class GradeTwo extends Grade{private String gradeName = "二班的";Student student = null;public GradeTwo(String type) {this.student = getStudent(type);}public void getGradeName(){System.out.println("小明是"+gradeName);student.getStudentType();}}abstract class Grade{abstract void getGradeName();public Student getStudent(String name){if("smart".equals(name)){return new SmartStudent();}else if ("stupid".equals(name)) {return new StupidStudent();}else {//System.out.println("类型比较一般");return null;}}}interface Student{void getStudentType();}class StupidStudent implements Student{public void getStudentType() {System.out.println("小明是笨的学生");}}class SmartStudent implements Student{public void getStudentType() {System.out.println("小明是聪明的学生");}}}




3 结果

小明是一班的小明是聪明的学生小明是二班的小明是聪明的学生-------------->小明是一班的小明是笨的学生小明是二班的小明是笨的学生