装饰模式

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

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

/**
 * @Author: subd
 * @Date: 2019/9/17 8:15
 * 装饰模式
 */
public class DecorationMode {

    public static abstract class Component {
        public abstract void Operation();
    }

    public static class ConcreteComponent extends Component {

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

    public static 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 static class ConcreteDecoratorA extends Decorator {
        private String addedState;

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

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

        private void AddedBehavior() {
        }
    }

    public static void main(String[] args) {
        /**
         * 装饰的方法是:
         * 首先用 ConcreteComponent 实例化对象c
         * 然后用 ConcreteDecoratorA 实例化从ca
         * 再用   ConcreteDecoratorB 实例化从cb
         */
        ConcreteComponent c = new ConcreteComponent();
        ConcreteDecoratorA ca = new ConcreteDecoratorA();
        ConcreteDecoratorB cb = new ConcreteDecoratorB();
        ca.setComponent(c);
        cb.setComponent(ca);
        cb.Operation();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值