美文网首页
桥接模式

桥接模式

作者: 码上述Andy | 来源:发表于2019-07-08 22:59 被阅读0次

    1.概念

    桥接模式是抽象与实现分离,做到修改互不影响。

    2.UML结构图

    image.png

    3.代码实现

    实现类接口

    /**
     * Created by ZW on 2019/7/8 22:33
     */
    public interface Car {
        void buildCar();
    }
    

    具体接口实现类

    /**
     * Created by ZW on 2019/7/8 22:34
     */
    public class Truck implements Car{
        @Override
        public void buildCar() {
            Logger.getLogger("Truck").info("the car is truck");
        }
    }
    
    /**
     * Created by ZW on 2019/7/8 22:34
     */
    public class Bus implements Car{
        @Override
        public void buildCar() {
            Logger.getLogger("Truck").info("the car is bus");
        }
    }
    

    抽象类

    /**
     * Created by ZW on 2019/7/8 22:35
     */
    public abstract class AbstractionCar {
        private Car mCar;
    
        public abstract void buildCar();
    
        public void setCar(Car car) {
            mCar = car;
        }
    
        public Car getCarIns(){
            return mCar;
        }
    }
    

    扩展抽象类

    /**
     * Created by ZW on 2019/7/8 22:46
     */
    public class RefinedAbstactionCar extends AbstractionCar{
        @Override
        public void buildCar() {
            getCarIns().buildCar();
        }
    }
    

    具体调用

    /**
     * Created by ZW on 2019/7/8 22:37
     */
    public class BridgeClient  {
        public void runCar(){
            AbstractionCar abstractionCar = new RefinedAbstactionCar();
    
            abstractionCar.setCar(new Bus());
            abstractionCar.buildCar();
    
            abstractionCar.setCar(new Truck());
            abstractionCar.buildCar();
        }
    }
    

    相关文章

      网友评论

          本文标题:桥接模式

          本文链接:https://www.haomeiwen.com/subject/jcaohctx.html