码迷,mamicode.com
首页 > 其他好文 > 详细

装饰模式

时间:2017-03-23 22:27:31      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:ati   cli   pac   int   code   new   对象   end   http   

技术分享

技术分享


从用户的角度看:需要知道基本类和装饰类之间的嵌套关系(大致能添加什么装饰功能) 并且这些装饰规则可以互相嵌套 来实现特定顺序的功能。

从实现者的角度看:让这些类真的可以嵌套

 

package com.dp.decorator1;
/**
 * 定义了一个对象接口 可以给这些对象动态的添加职责
 * @author 黄二狗
 *
 */
public interface Component {
  void operation();
}
package com.dp.decorator1;

/**
 *   被装饰的基础对象
 * @author 黄二狗
 *
 */
public class ConcreteComponent implements Component{

    
    @Override
    public void operation() {
      System.out.println("基础操作");    
    }
        
}
package com.dp.decorator1;

/**
 * 实现了Component 从外类来扩展Component类的功能 但对于Component来说,不需要知道Decorator的存在
 * @author 黄二狗
 *
 */
public abstract class Decorator implements Component{
   private Component component;
   
   public void setComponent(Component component)
   {
       this.component=component;
   }
   
   @Override
    public void operation() {
    
       if(component!=null)
       {
           component.operation();
       }
    }
  
}
package com.dp.decorator1;

/**
 * 具体的装饰对象,起到给Component添加职责的功能
 * 装饰类A可以有自己的一些操作
 * @author 黄二狗
 *
 */
public class ConcreteDecoratorA extends Decorator{
    //装饰类A的一个状态
    private String state="concreteDecorator__A";
    
    @Override
    public void operation() {

        super.operation();
        System.out.println(state);
    }
}
package com.dp.decorator1;

public class ConcreteDecoratorB extends Decorator{
  @Override
public void operation() {
    super.operation();
    addedBehavior();
}
  
  //装饰类B
  public void addedBehavior()
  {
      System.out.println("添加一些额外的行为");
  }
}
package com.dp.decorator1;

/**
 * 用户需要知道基本类和装饰类之间的嵌套关系
 * @author 黄二狗
 *
 */
public class Client {

    public static void main(String[] args) {
        //基础类
        ConcreteComponent concreteComponent=new ConcreteComponent();
        //装饰类A
        ConcreteDecoratorA decoratorA=new ConcreteDecoratorA();
        decoratorA.setComponent(concreteComponent);
        //装饰类B
        ConcreteDecoratorB decoratorB=new ConcreteDecoratorB();
        decoratorB.setComponent(decoratorA);
        //装饰链的调用
        decoratorB.operation();
    }
}

 

装饰模式

标签:ati   cli   pac   int   code   new   对象   end   http   

原文地址:http://www.cnblogs.com/HJL085/p/6607547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!