《桥接模式》像桥一样走入你的心里

1. 我们先来看一个产品图

这张图没有用桥接模式

在这里插入图片描述

2. 我们看看运用了桥接模式的产品图

用了桥接模式之后

在这里插入图片描述

3. 代码实现

品牌的接口

public interface Brand {
    void info();
}

抽象的产品类

public abstract class Product {
	//这里运用的就是组合的思想
    protected Brand brand;

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

    public abstract void info();
}

品牌的实现类

public class Apple implements Brand {
    @Override
    public void info() {
        System.out.print("苹果");
    }
}

产品实现类

public class Computer extends Product {


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

    @Override
    public void info() {
        brand.info();
        System.out.println("电脑");
    }
}

测试类

public class Client {
    public static void main(String[] args) {
        Brand brand = new Apple();

        Computer computer = new Computer(brand);
        computer.info();
    }
}

输出结果
在这里插入图片描述

原创文章 34 获赞 8 访问量 1156

猜你喜欢

转载自blog.csdn.net/qq_46225886/article/details/105731770