装饰器模式

来源:互联网 发布:ukcn中介怎么样 知乎 编辑:程序博客网 时间:2024/06/08 16:27

装饰器模式

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

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

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

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装饰完成
原创粉丝点击