大话设计模式读书笔记之装饰者模式

1.定义:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
2.UML类图
这里写图片描述

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

//装饰者模式抽象类
package com.guo.decoratorPattern;

public abstract class Component {

    public abstract void operation();
}
//具体操作的被装饰的类
package com.guo.decoratorPattern;

public class ConcreteComponent extends Component {

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

}
//装饰者抽象类
package com.guo.decoratorPattern;

public abstract class Decorator extends Component {

    private Component component;

    public Decorator(Component component) {
        super();
        this.component = component;
    }

    @Override
    public void operation() {
        if (component != null) {
            System.out.println("实际执行的是传入的Component,被装饰的是 :" + component.getClass().getName());
            component.operation();
        }
    }
}
//装饰者实现类
package com.guo.decoratorPattern;

public class DecoratorComponent extends Decorator {

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

    @Override
    public void operation() {
        super.operation();
        System.out.println("此处可以添加一些装饰类自己的行为。。。");
    }

}
//客户端调用示例
package com.guo.decoratorPattern;

public class DecoratorClient {

    public static void main(String[] args) {
        //实例化一个被装饰者
        Component concreteComponent = new ConcreteComponent();
        //实例化一个装饰者
        Component decoratorComponent = new DecoratorComponent(concreteComponent);

        decoratorComponent.operation();
    }
}

5.总结
这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值