29.装饰者模式

来源:互联网 发布:网络终端机服务器软件 编辑:程序博客网 时间:2024/05/28 18:44
1.装饰者模式中要求,装饰者中含有被装饰者的引用

2.装饰者模式中要求,装饰者和被装饰者应该实现同一个类型


被装饰者

public class HelloWorld {public static void main(String[] args)throws Exception{}public void close() {System.out.println("test close");}}

装饰者

public class test2 {//装饰者//关联关系HelloWorld hello;//被装饰者//Constructortest2(HelloWorld hello){this.hello = hello;}//对HelloWorld中的方法进行扩展public void close() {//扩展System.out.println("扩展代码1");hello.close();System.out.println("扩展代码2");}}

调用

public class test02 {public static void main(String[] args) {//创建被装饰者HelloWorld hw = new HelloWorld();//创建装饰者test2 t2 = new test2(hw);//通过执行装饰者中的方法间接去执行被装饰者中的方法t2.close();}}


原创粉丝点击