BridgePattern(桥接模式)

/**
 * 桥接模式
 * @author TMAC-J
 * 应用于多维度方案
 * 用组合的形式代替继承
 * 符合单一职责原则
 * 一个类只有一个引起他变化的原因
 * 增加程序灵活性
 */
public class BridgePattern {
    
    abstract class Road{
        Car car;
        void run(){};
    }
    
    abstract class Car{
        void showMyName(){};
    }
    
    public class Street extends Road{
        public void run(){
            car.showMyName();
            System.out.println("在街道上上奔驰");
        }
    }
    
    public class SpeedRoad extends Road{
        public void run(){
            car.showMyName();
            System.out.println("在高速路上奔驰");
        }
    }
    
    public class Bus extends Car{
        public void showMyName(){
            System.out.println("公交车");
        }
    }
    
    public class SedanCar extends Car{
        public void showMyName(){
            System.out.println("轿车");
        }
    } 
    
    public void test(){
        Street street = new Street();
        street.car = new Bus();
        street.run();//输出结果为公交车在街道上奔驰
        SpeedRoad speedRoad = new SpeedRoad();
        speedRoad.car = new SedanCar();
        speedRoad.run();//输出结果为轿车在高速路上奔驰
    }
    
}

 

posted @ 2016-12-28 11:02  麦子TMAC  阅读(219)  评论(0编辑  收藏  举报