天天看点

设计模式——桥接模式

桥接模式属于结构型模式,主要用于某一个类,需要体现两个维度上的特征!例如一碗面条的味道可能需要蔬菜和肉的类型两个维度描述(海带鸡丝面,酸菜牛肉面等),并且每一个维度不能使用基本类型的变量描述,需要使用类描述。

桥接模式一般是由接口 + 抽象类 + 实现类描述的!

接口描述一个维度,抽象类描述另一个维度,同时抽象类本身也是一个维度,实现类继承与抽象类!

然而抽象类并不是继承于接口,而是聚合关系。接口作为抽象类的成员变量。

设计模式——桥接模式
设计模式——桥接模式

/*
 * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved
 */

package com.pt.bridge;

/**
 * @description 蔬菜抽象接口
 * @author panteng
 * @date 17-2-7.
 */
public interface VegetablesType {
    public String getVegetables();
}      

VegetablesType

设计模式——桥接模式
设计模式——桥接模式
/*
 * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved
 */

package com.pt.bridge;

/**
 * @description 蔬菜实现类-海带
 * @author panteng
 * @date 17-2-8.
 */
public class Kelp implements VegetablesType {
    public String getVegetables(){
        return "海带";
    }
}      

Kelp

设计模式——桥接模式
设计模式——桥接模式
/*
 * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved
 */

package com.pt.bridge;

/**
 * @description 蔬菜实现类-酸菜
 * @author panteng
 * @date 17-2-8.
 */
public class Sauerkraut implements VegetablesType {
    public String getVegetables(){
        return "酸菜";
    }
}      

Sauerkraut

设计模式——桥接模式
设计模式——桥接模式
/*
 * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved
 */

package com.pt.bridge;

/**
 * @description 肉类抽象类
 * @author panteng
 * @date 17-2-7.
 */
public abstract class AbstractMeatType {
    VegetablesType vegetablesType;

    public abstract String getMeat();

    public String getTaste(){
        return vegetablesType.getVegetables() + this.getMeat();
    }

    public VegetablesType getVegetablesType(){
        return vegetablesType;
    }
    public void setVegetablesType(VegetablesType vegetablesType){
        this.vegetablesType = vegetablesType;
    }
}      

AbstractMeatType

设计模式——桥接模式
设计模式——桥接模式
/*
 * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved
 */

package com.pt.bridge;

/**
 * @description 肉类抽象类的实现 - 牛肉
 * @author panteng
 * @date 17-2-8.
 */
public class Beef extends AbstractMeatType {
    @Override
    public String getMeat(){
        return "牛肉";
    }
}      

Beef

设计模式——桥接模式
设计模式——桥接模式
/*
 * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved
 */

package com.pt.bridge;

/**
 * @description 肉类抽象类的实现 - 鸡肉
 * @author panteng
 * @date 17-2-8.
 */
public class Chicken extends AbstractMeatType {
    @Override
    public String getMeat(){
        return "鸡肉";
    }
}      

Chicken

设计模式——桥接模式
设计模式——桥接模式
/*
 * Copyright (c) 2017. Xiaomi.Co.Ltd All rights reserved
 */

package com.pt.bridge;

/**
 * @description 桥接模式的应用
 * @author panteng
 * @date 17-2-8.
 */
public class Client {
    public static void main(String[] arges){
        System.out.println("start... ...");
        Kelp kelp = new Kelp();
        Sauerkraut sauerkraut = new Sauerkraut();

        Beef beef = new Beef();
        beef.setVegetablesType(kelp);
        System.out.println(beef.getTaste());

        beef.setVegetablesType(sauerkraut);
        System.out.println(beef.getTaste());
    }
}      

测试