设计模式学习(结构型模式)—装饰模式(Decorator)

来源:互联网 发布:seo研究中心教程下载 编辑:程序博客网 时间:2024/06/04 18:36

装饰模式(Decorator) 

以对客户透明的方式来扩展对象的功能。 用户根据功能需求随意选取组成对象的成分,通过方法的链式调用来实现。 可以给对象动态的增加功能,比继承灵活性更大。


[java] view plaincopy
  1. public class TestDecorator {  
  2.   
  3. public static void main(String[] args) {  
  4.   
  5. Teacher t1=new SimpleTeacher();  
  6.   
  7. Teacher t2=new CppTeacher(t1);  
  8.   
  9. Teacher t3=new JavaTeacher(t2);  
  10.   
  11. t3.teach();  
  12.   
  13. //t.teach();  
  14.   
  15. }  
  16.   
  17. }  
  18.   
  19.   
  20.   
  21. abstract class Teacher{  
  22.   
  23. public abstract void teach();  
  24.   
  25. }  
  26.   
  27. class SimpleTeacher extends Teacher{  
  28.   
  29. public void teach(){  
  30.   
  31. System.out.println("Good Good Study, Day Day Up");  
  32.   
  33. }  
  34.   
  35. }  
  36.   
  37. class JavaTeacher extends Teacher{  
  38.   
  39. Teacher teacher;  
  40.   
  41. public JavaTeacher(Teacher t){  
  42.   
  43. this.teacher=t;  
  44.   
  45. }  
  46.   
  47. public void teach(){  
  48.   
  49. teacher.teach();  
  50.   
  51. System.out.println("Teach Java");  
  52.   
  53. }  
  54.   
  55. }  
  56.   
  57. class CppTeacher extends Teacher{  
  58.   
  59. Teacher teacher;  
  60.   
  61. public CppTeacher(Teacher t){  
  62.   
  63. this.teacher=t;  
  64.   
  65. }  
  66.   
  67. public void teach(){  
  68.   
  69. teacher.teach();  
  70.   
  71. System.out.println("Teach C++");  
  72.   
  73. }  
  74.   
  75. }   
0 0
原创粉丝点击