装饰模式

扩展原有类,一个旧类做参数,一个新类做返回值。

返回的新类扩展了旧类,即增加了新功能。



概述

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());
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值