zoukankan      html  css  js  c++  java
  • java设计模式--结构型模式--装饰模式

     1                                                 装饰模式
     2  概述
     3     动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
     4     
     5     
     6  适用性
     7     1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
     8 
     9     2.处理那些可以撤消的职责。
    10 
    11     3.当不能采用生成子类的方法进行扩充时。
    12              参与者
    13     1.Component
    14       定义一个对象接口,可以给这些对象动态地添加职责。
    15 
    16     2.ConcreteComponent
    17       定义一个对象,可以给这个对象添加一些职责。
    18 
    19     3.Decorator
    20       维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。
    21 
    22     4.ConcreteDecorator
    23       向组件添加职责。

    测试类:

     1 public class Test {
     2 
     3     public static void main(String[] args) {
     4         Man man = new Man();
     5         ManDecoratorA md1 = new ManDecoratorA();
     6         ManDecoratorB md2 = new ManDecoratorB();
     7         
     8         md1.setPerson(man);
     9         md2.setPerson(md1);
    10         md2.eat();
    11     }
    12 }
    1 public interface Person {
    2 
    3     void eat();
    4 }
    1 public class Man implements Person {
    2 
    3     public void eat() {
    4         System.out.println("男人在吃");
    5     }
    6 }
     1 public abstract class Decorator implements Person {
     2 
     3     protected Person person;
     4     
     5     public void setPerson(Person person) {
     6         this.person = person;
     7     }
     8     
     9     public void eat() {
    10         person.eat();
    11     }
    12 }
     1 public class ManDecoratorA extends Decorator {
     2 
     3     public void eat() {
     4         super.eat();
     5         reEat();
     6         System.out.println("ManDecoratorA类");
     7     }
     8 
     9     public void reEat() {
    10         System.out.println("再吃一顿饭");
    11     }
    12 }
    1 public class ManDecoratorB extends Decorator {
    2     
    3     public void eat() {
    4         super.eat();
    5         System.out.println("===============");
    6         System.out.println("ManDecoratorB类");
    7     }
    8 }

    用了大牛的代码做笔记,学习观摩不停进步...用了这么多框架,源码还是不易看懂啊

  • 相关阅读:
    topcoder srm 320 div1
    topcoder srm 325 div1
    topcoder srm 330 div1
    topcoder srm 335 div1
    topcoder srm 340 div1
    topcoder srm 300 div1
    topcoder srm 305 div1
    topcoder srm 310 div1
    topcoder srm 315 div1
    如何统计iOS产品不同渠道的下载量?
  • 原文地址:https://www.cnblogs.com/huzi007/p/4045278.html
Copyright © 2011-2022 走看看