Decorator

//在装饰模式中,必然有一个被提取出来最核心、最原始、最基本的接口或抽象类Component。
public abstract class Component {

    public abstract void operation();
    
}
//ConcreteComponent 最原始、最基本的接口或抽象类的实现。
public class ConcreteComponent extends Component {

    @Override
    public void operation() {
        System.out.println("执行最原始的操作!");
    }

}
//Decorator装饰类, 一般是一个抽象类。
public abstract class Decorator extends Component {

    //Decorator不一定有抽象方法,但它的属性里必然有一个 private 变量指向 Component。
    private Component component;

    public void setComponent(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        if (component != null) {
            component.operation();
        }
    }

}
//具体装饰类,就是要把最核心的、最原始的、最基本的东西装饰城啥模样。
public class ConcreteDecorator1 extends Decorator{

    @Override
    public void operation() {
        super.operation();  //先执行原Component的operation(),再执行本类的功能。
        doOpera();          //装饰的内容
    }
    
    private void doOpera(){
        System.out.println("执行具体操作1!");
    }
    
    //ConcreteDecorator1 独特的功能,区分ConcreteDecorator2。
    public void doJob(){
        System.out.println("i'm ConcreteDecorator1.");
    }

}
public class ConcreteDecorator2 extends Decorator{

    @Override
    public void operation() {
        super.operation();
        System.out.println("执行具体操作2!");
    }

    //ConcreteDecorator2 独特方法
    public void work(){
        System.out.println("i'm ConcreteDecorator2.");
    }
}
    public static void main(String[] args) {
        Component c = new ConcreteComponent();
        c.operation();
        
        System.out.println("----------------------");
        
        Decorator cd1 = new ConcreteDecorator1();
        cd1.setComponent(c);
        
        Decorator cd2 = new ConcreteDecorator2();
        cd2.setComponent(cd1);
        
        cd2.operation();
    }

执行结果:

执行最原始的操作!
----------------------
执行最原始的操作!
执行具体操作1!
执行具体操作2!

 

装饰模式:动态地给一个对象添加一些额外的职能,就增加功能来说,装饰模式比生成子类更加灵活。

Component是定义一个对象的接口,可以给这些对象动态地添加职责。
ConcreteComponent是定义了一个具体对象,也可以给这个对象添加一些职责。
Decorator,装饰抽象类,继承Component,从外类来扩展Component的功能,但对于Component来说,无需知道Decorator的存在。
至于ConcreteComponent就是具体的装饰对象,起到给Component添加职责的功能。

装饰模式就是利用setComponent(Component component)来对对象进行包装的。这样每个装饰的对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。

如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么也没有必要建立单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

装饰模式是为已有的功能动态添加更多功能的一种方式。

当系统需要新的功能的时候,是向旧的类中添加新的代码,这些新加的代码通常装饰了原有类的核心职责或主要行为。在主类中加入新的字段,新的方法或新的逻辑,从而增加主类的复杂度,而这些新加入的东西仅仅只是为了满足一些只在某个特定的情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象。因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。

装饰模式的优点:把类中的装饰功能从类中移除去掉,这样可以简化原有的类。有效地把类中的核心职责和装饰功能区分开来,而且可以去除相关类中重复的装饰逻辑。

原文地址:https://www.cnblogs.com/xuekyo/p/2399437.html