设计模式(1) ------------装饰者模式
来源:互联网 发布:ubuntu gcc最新版本 编辑:程序博客网 时间:2024/06/03 16:07
概述
JAVA23种设计模式之一,英文叫Decorator Pattern,又叫装饰者模式。装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。装饰模式的特点
(1) 装饰对象和真实对象有相同的接口。这样客户端对象就可以和真实对象相同的方式和装饰对象交互。 (2) 装饰对象包含一个真实对象的索引(reference) (3) 装饰对象接受所有的来自客户端的请求。它把这些请求转发给真实的对象。 (4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。
代码示例
以下示例中,ThirdParty.Java假定是一个现有的或者第三方的功能,因某种原因我们不能直接修改,它提供了一个sayMsg()的方法,而我们现在要做的是想在它的sayMsg()方法中增加一些我们想额外输出的内容,于是我们重写了一个Decorator.java类。MailTest.java是客户端测试程序。
ThirdParty.Java ===================== package decorator.saystr; public interface ThirdParty { public String sayMsg(); } Decorator.java ================== package decorator.saystr; public class Decorator implements ThirdParty { privateThirdParty thirdParty; public Decorator(ThirdParty thirdParty){ this.thirdParty= thirdParty; } publicString say(){ return"##"+ thirdParty.sayMsg() + "##"; } } MailTest.java ==================== package decorator.saystr; public class MailTest { public static void main(String[] args){ ThirdParty thirdPartyOne = newThirdParty(); Decorator decorator1 = newDecorator(thirdPartyOne); System.out.println(decorator1.say()); ThirdParty thirdPartyTwo = newThirdParty(); Decorator decorator2 = new Decorator(thirdPartyTwo); System.out.println(decorator2.say()); } }
转自:http://baike.baidu.com/view/2787758.htm
- 设计模式(三)--装饰者模式(1)
- 设计模式(1) ------------装饰者模式
- 设计模式-装饰者模式
- 设计模式:装饰者模式
- 设计模式:装饰者模式
- 设计模式: 装饰者模式
- 设计模式--装饰者模式
- 设计模式-装饰者模式
- 设计模式--装饰者模式
- 设计模式-装饰者模式
- 设计模式------------装饰者模式
- 设计模式--装饰者模式
- 设计模式:装饰者模式
- 设计模式-装饰者模式
- 设计模式-装饰者模式
- 设计模式-装饰者模式
- 设计模式--装饰者模式
- 【设计模式】装饰者模式
- UIColor,CGColor,CIColor三者的区别和联系
- 学习使用eclipse笔记
- Java中抽象类(Abstract Class)与接口(Interface)的区别?
- AS3组件
- 有关onsubmit return false 阻止form表单提交:js
- 设计模式(1) ------------装饰者模式
- Unity3D官方资源完全下载
- response
- Android-->Launcher拖拽事件详解
- Java中堆和栈创建对象的区别
- ubuntu下svn命令
- 批量添加顺序用户(如果要添加指定文件里的用户,稍作修改即可)
- jQuery获取dropdownList选择想的name值
- 提高代码debug的效率