大话设计模式--装饰模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiongchun11/article/details/77847927

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


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


public abstract class Component {

    public abstract void Operation();
}

public class ConcreteComponent extends Component {

    @Override
    public void Operation() {

    }
}

public abstract class Decorator extends Component {

    protected Component component;

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

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

public class ConcreteDecoratorA extends Decorator {

    private String addedState;

    @Override
    public void Operation() {
        super.Operation();
        addedState = "New State";
        System.out.println("对具体对象A的操作");
    }
}

public class ConcreteDecoratorB extends Decorator {

    @Override
    public void Operation() {
        super.Operation();
        AddedBehavior();
        System.out.println("具体装饰对象B的操作");
    }

    private void AddedBehavior() {

    }
}

public class Main {

    public static void main(String[] args) {
        ConcreteComponent c = new ConcreteComponent();
        ConcreteDecoratorA decoratorA = new ConcreteDecoratorA();
        ConcreteDecoratorB decoratorB = new ConcreteDecoratorB();

        decoratorA.setComponent(c);
        decoratorB.setComponent(decoratorA);
        decoratorB.Operation();

    }
}


猜你喜欢

转载自blog.csdn.net/xiongchun11/article/details/77847927