设计思想学习—装饰者模式

来源:互联网 发布:软件运营部门 编辑:程序博客网 时间:2024/06/01 08:51

装饰者模式

Decorator模式(别名Wrapper):动态将职责附加到对象上,若要扩展功能,装饰者提供了比继承更具弹性的代替方案。

UML图
取自大话设计模式

装饰者包含四个基本类

  • 抽象构件角色(Component):给出一个抽象接口,以规范准备接收附加责任的对象。

  • 具体构件角色(Concrete Component):定义将要接收附加责任的类。

  • 装饰角色(Decorator):持有一个构件(Component)对象的引用,并定义一个与抽象构件接口一致的接口。

  • 具体装饰角色(Concrete Decorator):负责给构件对象“贴上”附加的责任。

举个栗子
装饰者模式跟玩芭比娃娃有点像
Component就像是芭比娃娃玩具(外面的包装)
ConcreteComponent就好比刚刚从包装里面拿出来的芭比娃娃
Decorator就好比放芭比衣服和装饰的盒子
下面具体的实现就是芭比的衣服、头发之类的装饰。
然后就拿起芭比娃娃给她穿衣服、带头发就好了

//整套芭比娃娃玩具interface Component{    void toDo();}//芭比娃娃实体class ConcreteComponent implements Component{    @Override    public void toDo() {        System.out.println("我是芭比娃娃");    }}//装饰箱class Decorator implements Component{    private Component component;    public Decorator(Component component){        this.component=component;    }    @Override    public void toDo() {        component.toDo();    }}//芭比的衣服class Clothes extends Decorator{    public Clothes (Component component) {        super(component);    }    @Override    public void toDo() {        super.toDo();        System.out.println("穿上衣服");    }}//芭比的鞋子class Shoe extends Decorator{    public Shoe (Component component) {        super(component);    }    @Override    public void toDo() {        super.toDo();        System.out.println("穿鞋子");    }}public class Client {    public static void main(String[] args){        Component cct=new ConcreteComponent();        cct=new Shoe (new Clothes (cct));        cct.toDo();    }}/*输出我是芭比娃娃穿上衣服穿鞋子*/

显而易见的是被装饰类在编译的只有主要的一些功能,而在运行的时候却可以动态的给它加上其他的功能职责,而且继续增加其他的职责也不需要改动原类,只需要继续增加装饰类即可,完美实现了开闭原则。还有一个优点是这种动态增加比继承要灵活许多。

有意思的是当我看到这句代码的时候

cct=new Shoe (new Clothes (cct));

我突然发现跟我们的IO流太像了,经过查找资料发现,io正是运用了装饰者模式的一个典型例子,上图

这里写图片描述

原创粉丝点击