博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
装饰模式
阅读量:7182 次
发布时间:2019-06-29

本文共 1489 字,大约阅读时间需要 4 分钟。

hot3.png

装饰模式的结构

  装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。装饰模式可以在不使用创造更多子类的情况下,将对象的功能加以扩展。

  装饰模式的类图如下:

  在装饰模式中的角色有:

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

  ●  具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。

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

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

源代码

  抽象构件角色

public interface Component {     public void sampleOperation();    }

  具体构件角色

public class Decorator implements Component{ private Component component; public Decorator(Component component){     this.component = component;}@Override public void sampleOperation() {   // 委派给构件             component.sampleOperation();}    }

  装饰角色

public class Decorator implements Component{    private Component component;        public Decorator(Component component){        this.component = component;    }    @Override    public void sampleOperation() {        // 委派给构件        component.sampleOperation();    }    }

  具体装饰角色

public class ConcreteDecoratorA extends Decorator {    public ConcreteDecoratorA(Component component) {        super(component);    }        @Override    public void sampleOperation() {     super.sampleOperation();        // 写相关的业务代码    }}public class ConcreteDecoratorB extends Decorator {    public ConcreteDecoratorB(Component component) {        super(component);    }        @Override    public void sampleOperation() {      super.sampleOperation();        // 写相关的业务代码    }}

转载于:https://my.oschina.net/weiweiblog/blog/613471

你可能感兴趣的文章
Sublime Text使用入门8——扩展之命令
查看>>
EasyUI:easyui-combobox(清除选中项)
查看>>
window.location使用
查看>>
thinkphp框架开启页面gzip压缩
查看>>
gcc and g++分别是gnu的c & c++编译器
查看>>
centos 例行性工作转发外部邮箱
查看>>
工作中使用了一些触发器
查看>>
[每日一题] 11gOCP 1z0-052 :2013-09-7 The usage of the SQL*LOAD utility.............................
查看>>
我的友情链接
查看>>
async & await 的前世今生(Updated)
查看>>
揭开云“误”山的面纱
查看>>
Lua5.0 词法分析
查看>>
Solutions Log (2014-08)
查看>>
Java程序员从笨鸟到菜鸟之(七十八)细谈Spring(七)spring之JDBC访问数据库及配置详解...
查看>>
ElasticSearch(七)之elasticsearch集群搭建及参数详解
查看>>
Rails best practices
查看>>
Solaris 测试bonding的网卡是否可以 failover
查看>>
Ubuntu16.04 PPTP Server Setting
查看>>
你应该知道的16个Linux服务器监控命令
查看>>
Cisco Voip实验
查看>>