Java设计模式之桥接设计模式

桥接模式,是构造型的设计模式之一。桥接模式是基于类的最小设计原则。通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象与行为实现分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展。

  • Client:Bridge模式的使用者
  • Abstraction:抽象类接口(接口或抽象类)维护对行为实现(Implementor)的引用
  • Refined Abstraction:Abstraction子类
  • Implementor:行为实现类接口 (Abstraction接口定义了基于Implementor接口的更高层次的操作)
  • ConcreteImplementor:Implementor子类

 

下面我们通过一个简单的例子来理解桥接设计模式 

/*
* 桥接设计模式
* emaple:
* 一个机器有很多属性构成,比如说电脑有品牌、主板、CPU等。
* 而其中的机器和属性又分别有自己的特殊实现。
* 此时如果定义一个机器类将所有属性类封装进去实现势必会出现大量且重复的代码。
* 所以我们采用桥接模式将属性从机器中解耦然后使用组合或者聚合桥接起来。
* */
/*
* 定义抽象属性类
* */
abstract class Property{
    protected String name;
    public Property(String name){
        this.name = name;
    }
    abstract String show();
}

/*
* 定义抽象机器类
* */
abstract class Machine{
    /*
    * 使用聚合或组合的形式在机器类中引入属性类
    * */
    protected Property property;
    public Machine(Property property){
        this.property = property;
    }
    abstract void show();
}
/*
* 定义具体属性类(品牌:Brand)
* */
class Brand extends Property{
    public Brand(String name){
        super(name);
    }
    public String show(){
        return name;
    }
}

/*
* 定义具体机器类(电脑:Computer)
* */
class Computer extends Machine{
    public Computer(Brand brand){
        super(brand);
    }
    private String Chip(){
        return property.show();
    }
    public void show(){
        System.out.println("This is a "+Chip()+"Computer");
    }
}
public class Bridge {
    public static void main(String[] args) {
        Brand brandl = new Brand("Lenovo");
        Brand brandd = new Brand("Dell");
        Computer c1 = new Computer(brandd);
        Computer c2 = new Computer(brandl);
        c1.show();
        c2.show();
    }
}
/*
* Output:
This is a DellComputer
This is a LenovoComputer
* */

 

posted @ 2019-01-14 17:59  问月晚安  阅读(120)  评论(0编辑  收藏  举报