设计模式第四弹------装饰模式

1.1定义

        装饰模式就是动态地给一个对象添加新的功能,同时又不改变其结构。通用类图如下所示

 

u=2912453591,661136757&fm=214&gp=0.jpg

        我们分别来说明一下装饰模式的四个角色:

  • ComponentDec抽象构件

        ComponentDec是一个接口或者抽象类,定义我们最核心的对象。

  • ConcreteComponentDec具体构件

        ConcreteComponentDec是最核心接口或者抽象类的实现,需要装饰的就是它。

  • Decorator装饰角色

        一般是抽象类,实现接口或者抽象方法,在它的属性里必然有一个private变量指向ComponentDec抽象构件。

  • ConcreteDecortor具体装饰角色

        具体的装饰类,将最核心的东西装饰成其它东西。

        代码清单如下

//抽象构件
public abstract class Component{
    //抽象方法
    public abstract void operate();
}
//具体构件
public class ConcreteComponent extends Component{
     public void operate(){
         System.out.println("do Something");
     }
}
//抽象装饰类
public abstract class Decorator extends Component{
     private Component component =null;

     //通过构造函数传递被修饰者
     public Decorator(Component _component){
           this.component = _component;
     }

     public void operate(){
           this.component.operate();
     }
}
//具体的装饰类
public class ConcreteDecorator1 extends Decorator{
   //定义被修饰者
   public ConcreteDecorator1(Component _component){
      super(_component);
   }
   //定义自己的修饰方法
   private void method1(){
     System.out.println("method1 修饰");
   }

   public void operate(){
     this.method1();
     super.operate();
   }
}

//具体的装饰类
public class ConcreteDecorator2 extends Decorator{
   //定义被修饰者
   public ConcreteDecorator2(Component _component){
      super(_component);
   }
   //定义自己的修饰方法
   private void method2(){
     System.out.println("method1 修饰");
   }

   public void operate(){

     super.operate();
     this.method2();
   }
}
//场景类
public class Client{
   public static void main(String[] args){
      Component component =new ConcreteComponent();
      component = new ConcreteDecorator1(component);
      component = new ConcreteDecorator2(component);
      component.operate();
   }
}

 输出结果

    method1 修饰
    do Something
    method2 修饰

1.2优点

  • 装饰类和被装饰类,相互不耦合。
  • 装饰模式是继承关系的一个替代方案。
  • 可以动态的扩展一个实现类的功能。

1.3缺点

  • 尽量减少装饰类的数量,以便降低系统的复杂度。

1.4场景

  • 需要动态的给一个对象增加功能。

转载于:https://my.oschina.net/wuchanghao/blog/1822161

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值