装饰者模式

装饰者模式的实现:装饰者模式是在不必改变原类文件和使用继承的情况下,动态扩展一个对象的功能,它是通过创建一个包装对象,来装饰和包裹真实的对象。
优点:装饰者模式和继承关系都是要扩展对象的功能,但装饰者模式可以提供比继承更多的灵活性。
缺点:灵活性是更好了,却增加了对象的复杂性

           装饰者模式会导致设计中出现许多小类,如果过度使用,会使程序变得很复杂。

还是举个例子比较容易理解:

1.创建IthirdParty接口

package decorator;
/**
 * 抽象类接口
 * @author lyh
 *
 */
public interface IthirdParty {
	public String sayMsg();
}
2.创建IthirdParty接口的实现类 ThirdParty
package decorator;
/**
 * 具体类
 * @author lyh
 *
 */
public class ThirdParty implements IthirdParty{

	@Override
	public String sayMsg() {
		return "Hello";
	}
}
3.创建ThirdParty的装饰类Decorator1,也实现IthirdParty接口
package decorator;
/**
 * 具体装饰类1
 * @author lyh
 *
 */
public class Decorator1 implements IthirdParty{
	private IthirdParty thirdParty;
	public Decorator1(IthirdParty thirdParty){
		this.thirdParty=thirdParty;
	}
	
	@Override
	public String sayMsg() {
		return "##1"+thirdParty.sayMsg()+"##1";
	}

}
4.创建ThirdParty的装饰类Decorator2,也实现IthirdParty接口
package decorator;
/**
 * 具体装饰类2
 * @author lyh
 *
 */
public class Decorator2 implements IthirdParty{
	private IthirdParty ithirdParty;
	public Decorator2(IthirdParty ithirdParty){
		this.ithirdParty=ithirdParty;
	}
	@Override
	public String sayMsg() {
		return "##2"+ithirdParty.sayMsg()+"##2";
	}
}

5.创建测试类Test

package decorator;
/**
 * @author lyh
 *
 */
public class Test {
	public static void main(String args[]){
		IthirdParty thirdPartyOne = new ThirdParty();
		IthirdParty decorator1 =  new Decorator1(thirdPartyOne);
		IthirdParty decorator2 =  new Decorator2(decorator1);
		
		System.out.println(decorator2.sayMsg());
	}
}


输出结果是:##2##1Hello##1##2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值