设计模式--装饰模式

        为已有功能动态添加更多功能的一种方式

        客户端可以根据需要,有选择地,按顺序地使用装饰功能包装对象。

        Decorator 继承了Component ,ConcreteDecorator 给具体的 ConcreteComponent 进行装饰,添加新的功能或职责。

Component类

public interface Component {
    void Operation();
}

ConcreteComponent类

public class ConcreteComponent implements Component {
    @Override
    public void Operation() {
        System.out.println("具体操作对象");
    }
}

ConcreteDecorator

public abstract class Decorator implements 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();
        addBehavior();
        System.out.println("具体装饰对象B操作");
    }

    private void addBehavior() {

    }
}

客户端调用

public class Client {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        ConcreteDecoratorA decoratorA = new ConcreteDecoratorA();
        ConcreteDecoratorB decoratorB = new ConcreteDecoratorB();
        // 具体装饰类A 修饰 ConcreteComponent
        decoratorA.setComponent(component);
        // 具体装饰类B 再修饰 装饰类A
        decoratorB.setComponent(decoratorA);
        decoratorB.Operation();
        /**
         * 具体操作对象
         * 具体装饰对象A操作
         * 具体装饰对象B操作
         */
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值