装饰者模式

1.应用场景
当一个主体A最多拥有n个部件并且每个部件都可没有时,如果用类来描述A及其部件,那最多可以用到 2n 个类,这时明显不合理。如果把所有部件放在一个类里则会造成这个类过于庞大,不易于维护。
2.解决方案
采用递归的思想,让主体A和其部件实现同一个接口,并且部件内包含实现接口。
3.实现代码

 主体A和其部件都应该实现的接口
 public interface TopInterface{
     void execute();
     String getDescription();
 }   

  主体A

  public class A implements TopInterface{
    public void execute(){
        System.out.println("A is executing");
    }
    public String getDescription(){
        return "This is A";
    }
 }

  装饰者抽象类
  public abstract Decorator extends TopInterface{

}
  部件Aa
  public class Aa implements TopInterface{
    private TopInterface t;
    //get,set
    public Aa(TopInterface t){
        this.t = t;
    }
    public void execute(){
        t.execute();
        System.out.println("Aa is executing");
    }
    public String getDescription(){
        return t.getDescription() + "This is Aa";
    }
}

   部件Ab
   public class Ab implements TopInterface{
    private TopInterface t;
    //get,set
    public Ab(TopInterface t){
        this.t = t;
    }
    public void execute(){
        t.execute();
        System.out.println("Ab is executing");
    }
    public String getDescription(){
        return t.getDescription() + "This is Ab";
    }

}
    测试类
    public class Test{
    public static void main(String args[]){
        A a = new A();
        Aa aa = new Aa(a);
        Ab ab = new Ab(a);
        ab.execute();
        System.out.println(ab.getDescription());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值