装饰者模式

来源:互联网 发布:金枝玉叶电影知乎 编辑:程序博客网 时间:2024/06/05 00:39
装饰者模式的实现:装饰者模式是在不必改变原类文件和使用继承的情况下,动态扩展一个对象的功能,它是通过创建一个包装对象,来装饰和包裹真实的对象。
优点:装饰者模式和继承关系都是要扩展对象的功能,但装饰者模式可以提供比继承更多的灵活性。
缺点:灵活性是更好了,却增加了对象的复杂性

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

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

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());}}


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

0 0
原创粉丝点击