23种设计模式-桥接模式

Posted yppaopao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了23种设计模式-桥接模式相关的知识,希望对你有一定的参考价值。

桥接模式是将抽象部分与它的实现部分分离,使他们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。

技术图片

 

 

技术图片

 

 

 技术图片

 

 技术图片

 

 技术图片

 

 技术图片

 

 示例:

  品牌接口类

package factory.bridge;
//品牌
public interface Brand {
    void info();
}

两个实现了品牌的电脑类

package factory.bridge;
//苹果品牌
public class Apple implements Brand {
    @Override
    public void info() {
        System.out.println("苹果");

    }
}
package factory.bridge;
//联想品牌
public class Lenovo implements Brand {
    @Override
    public void info() {
        System.out.println("联想");

    }
}

一个抽象的电脑类 在电脑和品牌之间创建了一个桥

package factory.bridge;
//抽象的电脑类型
public  abstract class Computer {
    //组合, 品牌    桥
    //通过组合的方式在电脑和品牌类之间搭建了一个桥
    protected Brand brand;

    public Computer(Brand brand) { //有参构造
        this.brand = brand;
    }

    public void info(){
        brand.info(); //自带品牌   电脑的信息
    }
}


class Desktop extends Computer{

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

    @Override
    public void info() {
        super.info();

        System.out.println("台式机");
    }
}

class Laptop extends Computer{

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

    @Override
    public void info() {
        super.info();

        System.out.println("笔记本");
    }
}

测试类

package factory.bridge;

public class Test {
    public static void main(String[] args) {
        //苹果笔记本
        Computer computer = new Laptop(new Apple());
        computer.info();
        //联想台式机
        Computer computer2 = new Desktop(new Lenovo());
        computer2.info();

    }
}

 

以上是关于23种设计模式-桥接模式的主要内容,如果未能解决你的问题,请参考以下文章

23种设计模式-结构模式-桥接模式

23种设计模式-桥接模式(安卓应用场景介绍)

23种设计模式——桥接模式单一职责

23种设计模式-桥接模式

23种设计模式--桥接模式

23种设计模式学习之桥接模式