設計模式8——橋接模式

設計模式8——橋接模式




程式碼實現:

package com.ghl.bridge;

/**
 * @ProjectName DesignPattern
 * @ClassName brand
 * @Date 2020/8/27 22:10
 * @Author gaohengli
 * @Version 1.0
 */
//橋接模式
    //品牌
public interface Brand {

    void info();
}
package com.ghl.bridge;

/**
 * @ProjectName DesignPattern
 * @ClassName Lenovo
 * @Date 2020/8/27 22:11
 * @Author gaohengli
 * @Version 1.0
 */
//蘋果品牌
public class Apple implements Brand {
    @Override
    public void info() {
        System.out.println("蘋果");
    }
}
package com.ghl.bridge;

/**
 * @ProjectName DesignPattern
 * @ClassName Lenovo
 * @Date 2020/8/27 22:11
 * @Author gaohengli
 * @Version 1.0
 */
//聯想品牌
public class Lenovo implements Brand {
    @Override
    public void info() {
        System.out.println("聯想");
    }
}
package com.ghl.bridge;

/**
 * @ProjectName DesignPattern
 * @ClassName Computer
 * @Date 2020/8/27 22:16
 * @Author gaohengli
 * @Version 1.0
 */
//抽象的電腦類型類
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 com.ghl.bridge;

/**
 * @ProjectName DesignPattern
 * @ClassName Test
 * @Date 2020/8/27 22:29
 * @Author gaohengli
 * @Version 1.0
 */
//測試
public class Test {

    public static void main(String[] args) {
        //蘋果筆記型電腦
        Computer laptop = new Laptop(new Apple());
        laptop.info();

        //聯想台式機
        Computer desktop = new Desktop(new Lenovo());
        desktop.info();
    }
}