桥接模式

桥接模式

概述

桥接模式是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化的桥接,来实现二者的解耦

例子

电脑品牌有苹果,联想,戴尔等
电脑种类有台式机,笔记本,平板,一体机
品牌和机型组合的实现

package com.example.designPattern23.bridge;

/**
 * 功能描述
 *
 * @since 2022-05-18
 */
public interface Brand {
    void info();
}
package com.example.designPattern23.bridge;

/**
 * 功能描述
 *
 * @since 2022-05-18
 */
public class Apple implements Brand {
    @Override
    public void info() {
        System.out.println("apple");
    }
}

package com.example.designPattern23.bridge;

/**
 * 功能描述
 *
 * @since 2022-05-18
 */
public class Lenovo implements Brand {
    @Override
    public void info() {
        System.out.println("lenovo");
    }
}

package com.example.designPattern23.bridge;

/**
 * 功能描述
 *
 * @since 2022-05-18
 */
public class Computer {
    protected Brand brand;

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

    void info() {
        brand.info();
    }
}


class Desktop extends Computer {
    public Desktop(Brand brand) {
        super(brand);
    }

    @Override
    void info() {
        super.info();
        System.out.println(" Desktop");
    }
}

class Laptop extends Computer {
    public Laptop(Brand brand) {
        super(brand);
    }

    @Override
    void info() {
        super.info();
        System.out.println(" Laptop");
    }
}
package com.example.designPattern23.bridge;

/**
 * 功能描述
 *
 * @since 2022-05-18
 */
public class test {
    public static void main(String[] args) {
        Desktop desktop = new Desktop(new Lenovo());
        desktop.info();

        Laptop laptop = new Laptop(new Apple());
        laptop.info();
    }
}

posted @ 2022-05-18 20:50  Oh,mydream!  阅读(25)  评论(0编辑  收藏  举报