设计模式——装饰模式

来源:互联网 发布:js随机数1到22 编辑:程序博客网 时间:2024/06/17 17:44

装饰模式

装饰模式
  动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
  如同我们人要传衣服一样,每天可以穿的衣服有很多,我们可以任意选择几件衣服穿在自己身上,不喜欢也可以随时替换掉身上的衣服。衣服就好比额外的外形修饰,它们可以一层一层穿在我们身上,对我们的外在起到一定的装饰作用。
  
  装饰模式结构图
  这里写图片描述

其中:
1.Component(被装饰对象的基类) 定义一个对象接口,可以给这些对象动态地添加职责。
2.ConcreteComponent(具体被装饰对象)定义一个对象,可以给这个对象添加一些职责。
3.Decorator(装饰者抽象类)维持一个指向Component实例的引用,并定义一个与Component接口一致的接口。
4.ConcreteDecorator(具体装饰者) 具体的装饰对象,给内部持有的具体被装饰对象,增加具体的职责。

具体代码如下:

public class Person {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public void show() {        System.out.println( name + "的穿衣搭配");    }}public class TShirtDecorate extends Person {    private Person component;    public TShirtDecorate(Person component) {        this.component = component;    }    @Override    public void show() {        System.out.println("穿T-shirt");        component.show();    }}public class JeanDecorate extends Person {    private Person component;    public JeanDecorate(Person component) {        this.component = component;    }    @Override    public void show() {        System.out.println("穿牛仔裤");        component.show();    }}public class CoatDecorate extends Person {    private Person component;    public CoatDecorate(Person component) {        this.component = component;    }    @Override    public void show() {        System.out.println("穿外套");        component.show();    }}public class Test {    public static void main(String[] args) {        Person p = new Person();        p.setName("小菜");        CoatDecorate coatDecorate = new CoatDecorate(new JeanDecorate(new TShirtDecorate(p)));        coatDecorate.show();    }}

代码中:
Person类就是ConcreteComponent(被装饰类的具体实现类)
CoatDecorate 等类就是ConcreteDecorator(具体装饰者)

总结:
装饰模式的有点就是把类中的装饰功能从类中搬移去除,这样就可以简化原有的类。有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。

原创粉丝点击