天天看点

设计模式:装饰模式-decorator

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

设计模式:装饰模式-decorator

实际上就是decorator与concreteComponent是同一层次的可以替换的,在decorator中包含一个component对象,通过该对象调用原本的服务,并在该对象附近增加新服务

装饰模式的优点

(1)装饰模式与继承关系的目的都是要扩展对象的功能,但是装饰模式可以提供比继承更多的灵活性。装饰模式允许系统动态决定“贴上”一个需要的“装饰”,或者除掉一个不需要的“装饰”。继承关系则不同,继承关系是静态的,它在系统运行前就决定了。
(2)通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。
           

装饰模式的缺点

由于使用装饰模式,可以比使用继承关系需要较少数目的类。使用较少的类,当然使设计比较易于进行。但是,在另一方面,使用装饰模式会产生比使用继承关系更多的对象。更多的对象会使得查错变得困难,特别是这些对象看上去都很相像。
           

代码:

Main

public class Main {

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

        Component A=new ConcreteDecoratorA(component);
        A.sampleOperation();

        Component B=new ConcreteDecoratorB(component);
        B.sampleOperation();
    }

}
           

interface:Component

public interface Component {
    public void sampleOperation();
}
           

imp:Decorator

public class Decorator implements Component {

    private Component componet;
    @Override
    public void sampleOperation() {
        this.componet.sampleOperation();
        System.out.println("this is operation");
    }
    public Decorator(Component component) {
        this.componet=component;
    }

}
           

imp:ConcreteComponent

public class ConcreteComponent implements Component{

    @Override
    public void sampleOperation() {
        System.out.println("sample operation");
    }

}
           

imp:ConcreteDecoratorA

public class ConcreteDecoratorA extends Decorator {

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

    @Override
    public void sampleOperation() {
        super.sampleOperation();
        System.out.println("concrete A");
    }

}
           

imp:ConcreteDecoratorB

public class ConcreteDecoratorB extends Decorator {

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

    @Override
    public void sampleOperation() {
        super.sampleOperation();
        System.out.println("concrete B");
    }

}
           

继续阅读