装饰器模式

设计模式的意义在于:面向业务内容、业务数据结构和系统架构,高内聚低耦合、优雅的将平面逻辑立体化。

 1 package designPattern;
 2 /**
 3  * 装饰器模式
 4  * @author Administrator
 5  */
 6 public class B12_DecoratorTest {
 7 
 8     /**
 9      *  动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
10      *  适用于
11      *  1,在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责.
12      *  2,处理那些可以撤消的职责.
13      *  3,当不能采用生成子类的方法进行扩充时.
14      */
15     public static void main(String[] args) {
16         ManDecortor man=new ManDecortor();
17         Man1 man1=new Man1();
18         Man2 man2=new Man2();
19         man1.setP(man);
20         man1.eat();
21         man2.setP(man1);
22         man2.eat();
23     }
25 }
26 //1.Component 定义一个对象接口,可以给这些对象动态地添加职责。
27 interface PersonDecorator
28 {
29     void eat();
30 }
31 //2.ConcreteComponent 定义一个对象,可以给这个对象添加一些职责。
32 class ManDecortor implements PersonDecorator
33 {
34     public void eat()
35     {
36         System.out.println("||||||||||");
37         System.out.println("男人在吃...");
39     }
40 }
41 //3.Decorator 维持一个指向Component对象的指针,并定义一个与Component接口一致的接口
42 abstract class Decorator implements PersonDecorator
43 {
44     protected PersonDecorator p;
45     
46     public void setP(PersonDecorator p) {
47         this.p = p;
48     }
49     public void eat() {
50         p.eat();        
51     }    
52 }
53 // 4.ConcreteDecorator 向组件添加职责
54 class Man1 extends Decorator
55 {
56     public void eat() {
57         super.eat();
58         System.out.println("======");
59         System.out.println("男人111在吃...");
60     }
61 }
62 class Man2 extends Decorator
63 {
64     public void eat() {
65         super.eat();
66         System.out.println("~~~~~~");
67         System.out.println("男人222在吃...");
68         reEat();
69     }
70     public void reEat()
71     {
72         System.out.println("再吃一顿...");
73     }
74 }

 

环境:JDK1.6,MAVEN,tomcat,eclipse

源码地址:https://files.cnblogs.com/files/xiluhua/designPattern.rar

欢迎亲们评论指教。

posted @ 2015-04-10 10:03  xiluhua  阅读(153)  评论(0编辑  收藏  举报