装饰器模式

装饰器模式

简单的说,装饰器模式可能动态的给一个对象增加额外的功能。

就像人类通过各种服饰来打扮自己一样,对象通过装饰器模式打扮自己,从而拥有更多功能。

先看下装饰器模式的类图:

UML类图

这里写图片描述

图1 装饰器模式类图

类图中的Component是一个接口,ConcreteComponent是将要被装饰的具体类。Decorator是装饰器基础抽象类,该抽象类实现了Component接口。Decorator有两个具体的装饰器类,这两个装饰器类实现了不同的装饰效果。看下实现代码:

代码实现

Component类

/**
 * <p>文件描述: 需要被装饰的类的接口</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:50
*/
public interface Component {
    void operation();
}

ConcreteComponent类

/**
 * <p>文件描述: 需要被装饰的具体类</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:52
*/
public class ConcreteComponent implements Component {

    @Override
    public void operation() {
        System.out.println("我是需要被装饰的类");
    }
}

Decorator类

/**
 * <p>文件描述: 装饰器基础抽象类</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:55
*/
public abstract class Decorator implements Component {

    private Component component;

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

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

ConcreteDecoratorA类

/**
 * <p>文件描述: 具体装饰器A</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:56
*/
public class ConcreteDecoratorA extends Decorator {

    @Override
    public void operation() {
        System.out.println("通过装饰器A装饰");
        super.operation();
        System.out.println("装饰器A装饰完成");
    }
}

ConcreteDecoratorB类

/**
 * <p>文件描述: 具体装饰器B</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:58
*/
public class ConcreteDecoratorB extends Decorator {

    @Override
    public void operation() {
        System.out.println("通过装饰器B装饰");
        super.operation();
        System.out.println("装饰器B装饰完成");
    }
}

DecoratorDemo类

/**
 * <p>文件描述: 装饰器模式Demo类</p>
 *
 * @Author luanmousheng
 * @Date 17/8/3 下午9:59
*/
public class DecoratorDemo {

    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        //通过装饰器A装饰
        Decorator decoratorA = new ConcreteDecoratorA();
        decoratorA.setComponent(component);
        decoratorA.operation();
        //通过装饰器B装饰
        Decorator decoratorB = new ConcreteDecoratorB();
        decoratorB.setComponent(component);
        decoratorB.operation();
    }
}

Demo类输出结果

通过装饰器A装饰
我是需要被装饰的类
装饰器A装饰完成
通过装饰器B装饰
我是需要被装饰的类
装饰器B装饰完成
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值