装饰者模式
来源:互联网 发布:金枝玉叶电影知乎 编辑:程序博客网 时间:2024/06/05 00:39
装饰者模式的实现:装饰者模式是在不必改变原类文件和使用继承的情况下,动态扩展一个对象的功能,它是通过创建一个包装对象,来装饰和包裹真实的对象。
优点:装饰者模式和继承关系都是要扩展对象的功能,但装饰者模式可以提供比继承更多的灵活性。
缺点:灵活性是更好了,却增加了对象的复杂性
5.创建测试类Test
优点:装饰者模式和继承关系都是要扩展对象的功能,但装饰者模式可以提供比继承更多的灵活性。
缺点:灵活性是更好了,却增加了对象的复杂性
装饰者模式会导致设计中出现许多小类,如果过度使用,会使程序变得很复杂。
还是举个例子比较容易理解:
1.创建IthirdParty接口
package decorator;/** * 抽象类接口 * @author lyh * */public interface IthirdParty {public String sayMsg();}2.创建IthirdParty接口的实现类 ThirdParty
package decorator;/** * 具体类 * @author lyh * */public class ThirdParty implements IthirdParty{@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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());}}
0 0
- 装饰者模式(Derector)
- 装饰者模式
- Decorator 装饰者模式
- 装饰者设计模式
- 装饰者模式
- 装饰者模式
- 装饰者模式
- 装饰者模式(Decorator)
- 装饰者模式
- 装饰者模式
- 装饰者模式
- 装饰者模式 DecoratorPattern
- 设计模式 - 装饰者
- 装饰者模式
- 装饰者模式
- 装饰者模式 - 2
- 装饰者模式
- 装饰者模式
- PDF阅读器系列之--MuPDF源码分析过程(一)
- GIMP 创建arm LCD上显示的图片
- Java排序算法(十)--桶排序
- 获取间隔N小时的时间戳
- Android创建图片图库不显示问题
- 装饰者模式
- Android中的android:layout_width和android:width
- curl
- Bitmap too large to be uploaded into a texture
- EFI
- bzoj1598: [Usaco2008 Mar]牛跑步
- curl应用总结(二)
- HDU 2768 Cat vs. Dog (二分图)
- Java构造和解析Json数据的两种方法详解一