1. 手机操作问题

  不同后记类型的不同品牌实现打电话功能

   传统解决方式

   缺点:如果此时想要在增加一种手机样式(旋转式),那么就需要在手机样式下同时在增加不同品牌的手机;同样如果想要增加一个品牌(huawei),那么就需要在每一种样式下增加品牌,会增加很多类;

 

2. 桥接模式

  将实现和抽象放在两个不同的类层次中,两个层次可以独立改变

 

public interface Brand {

    /**
     *  打电话
     */
    void call();
}
public class Xiaomi implements Brand {

    @Override
    public void call() {
        System.out.println("小米手机打电话");
    }
}
public class ViVo implements Brand {

    @Override
    public void call() {
        System.out.println("vivo手机打电话");
    }
}
public abstract class Phone {

    private Brand brand;

    public Phone(Brand brand) {
        this.brand = brand;
    }

    public void call(){
        this.brand.call();
    }
}
public class UpRightPhone extends Phone {

    public UpRightPhone(Brand brand) {
        super(brand);
    }

    @Override
    public void call() {
        super.call();
        System.out.println(" 直立手机 ");
    }
}
public class FoldedPhone extends Phone {


    public FoldedPhone(Brand brand) {
        super(brand);
    }

    @Override
    public void call() {
        super.call();
        System.out.println(" 折叠手机 ");
    }
}
public class Client {

    public static void main(String[] args) {
        Phone phone1 = new UpRightPhone(new ViVo());
        phone1.call();

        FoldedPhone phone2 = new FoldedPhone(new Xiaomi());
        phone2.call();
    }
}

  使用桥接模式,此时如果想要在增加一种旋转样式的手机,只需要继承Phone抽象类,重写call方法,不用像之前传统方式那样要写很多类。

posted on 2024-04-08 21:12  homle  阅读(1)  评论(0编辑  收藏  举报