第4章 结构型模式-装饰模式

2022-06-16  本文已影响0人  一介书生独醉江湖
结构型模式的目的是通过组合类或对象产生更大结构,以适应更高层次的逻辑需求;
结构型模式共有7种:
■ 代理模式
■ 装饰模式
■ 适配器模式
■ 组合模式
■ 桥梁模式
■ 外观模式
■ 享元模式
一、装饰模式简介
■ 动态地给一个对象添加一些额外的职责;
  就增加功能来说,装饰模式比生成子类更为灵活;
image.png
■ 抽象构件(Component)角色:该角色用于规范需要装饰的对象(原始对象);
■ 具体构件(Concrete Component)角色:该角色实现抽象构件接口,定义一个需要装饰的原始类;
■ 装饰(Decorator)角色:该角色持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口;
■ 具体装饰(Concrete Decorator)角色:该角色负责对构件对象进行装饰;
public interface Component {
    void operation();
}
public class ConcreteComponent implements Component{
    @Override
    public void operation() {
        // 具体的构件
        System.out.println("具体的构件逻辑");
    }
}
public abstract class Decorator implements Component{

    private Component component = null;

    public Decorator(Component component){
        this.component = component;
    }

    @Override
    public void operation(){
        this.component.operation();
    }

}
public class ConcreteDecorator extends Decorator{

    public ConcreteDecorator(Component component) {
        super(component);
    }

    // 定义自己的方法
    public void method(){
        System.out.println("修饰");
    }

    @Override
    public void operation(){
        this.method();
        super.operation();
    }
}
public class ClientDemo {

    public static void main(String[] args){
        Component component = new ConcreteComponent();

        // 进行装饰
        component = new ConcreteDecorator(component);

        component.operation();
    }
}
# 控制台输出:
修饰
具体的构件逻辑
二、装饰模式的优缺点
# 装饰模式的优点:
■ 装饰类和被装饰类可以独立发展,而不会相互耦合;
■ 装饰模式是继承关系的一个替代方案;
■ 装饰模式可以动态地扩展一个实现类的功能;

# 装饰模式的缺点:
■ 多层的装饰是比较复杂的;
三、装饰模式的使用场景
■ 需要扩展一个类的功能,或给一个类增加附加功能;
■ 需要动态地给一个对象增加功能,这些功能可以再动态地撤销;
■ 需要为一批类进行改装或加装功能;
四、装饰模式的实例
image.png
/**
 * 汽车接口Car
 */
public interface Car {
    public void show();
}
/**
 * 奔驰车(裸车、需要装饰)
 */
public class Benz implements Car{
    @Override
    public void show() {
        System.out.println("奔驰车的默认颜色是黑色");
    }
}
/**
 * 汽车修饰抽象类
 */
public abstract class CarDecorator implements Car{

    private Car car = null;

    public CarDecorator(Car car){
        this.car = car;
    }

    @Override
    public void show(){
        this.car.show();
    }
}
/**
 * 汽车修饰实现类
 */
public class ConcreteCarDecorator extends CarDecorator{


    public ConcreteCarDecorator(Car car) {
        super(car);
    }

    // 给车进行彩绘
    private void print(){
        System.out.println("彩绘紫色");
    }
    // 安装GPS
    private void setGps(){
        System.out.println("加装GPS");
    }

    @Override
    public void show(){
        super.show();
        print();
        setGps();
    }
}
/**
 * 应用程序
 */
public class ClientDemo {

    public static void main(String[] args){
        Car car = new Benz();
        // 对奔驰车进行装饰
        CarDecorator carDecorator = new ConcreteCarDecorator(car);
        carDecorator.show();
    }
}
# 控制台输出:
奔驰车的默认颜色是黑色
彩绘紫色
加装GPS
参考:
摘录 《设计模式(Java版)》韩敬海主编;(微信读书APP中有资源,可以直接阅读)
上一篇 下一篇

猜你喜欢

热点阅读