设计模式-装饰者模式学习

装饰者(Component-Decorator)模式

动态的将责任附加到对象上,想要扩展功能,装饰者提供有别于继承的另外一种选择。
- 对扩展开放,对修改关闭
- 装饰者和被装饰者都有相同的超类型
- 装饰者可以在所委托被装饰者的行为之前或之后,加上自己的行为,以达到特定的目的。
- 对象可以在任何时候被装饰,所以可以在运行时动态地、不限量的用装饰者来装饰对象

个人总结

  1. 利用继承实现父类(被修饰者)的抽象方法。
  2. 子类方法需要定义构造器,传入父类被修饰者)对象
  3. 修饰:多次实例化,将上次的实例对象作为本次的实例化对象的traget传入。

具体实例

如手抓饼案例,根据加的菜不同,所得价格不同。
这里写图片描述

主题代码:

public abstract class Cake {
public abstract String getDescription();
public abstract double getcost();

}

观察者1:手抓饼

public class ShreddedCake extends Cake{
@Override
public double getcost() {
    // TODO Auto-generated method stub
    return 5.0;
}

@Override
public String getDescription() {
    // TODO Auto-generated method stub
    return "Shredded Cake";
}

}

观察者2:加蛋
public class AddEggCake extends Cake{

public Cake cake;
public AddEggCake(Cake cake) {
    // TODO Auto-generated constructor stub
    this.cake = cake;
}
@Override
public String getDescription() {
    // TODO Auto-generated method stub
    return "agg-"+cake.getDescription();
}

@Override
public double getcost() {
    // TODO Auto-generated method stub
    return cake.getcost()+3;
}

}

观察者3:加肉

public class AddMeatCake extends Cake{
private Cake cake;
public AddMeatCake(Cake cake ){
    // TODO Auto-generated constructor stub
    this.cake = cake;
}
@Override
public String getDescription() {
    // TODO Auto-generated method stub
    return "meat-"+cake.getDescription();
}
@Override
public double getcost() {
    // TODO Auto-generated method stub
    return cake.getcost()+5;
}

}

Main测试:

public class MainTest {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Cake cake = new ShreddedCake();
    System.out.print("This Cake is a "+cake.getDescription()+" , ");
    System.out.println("and price is "+cake.getcost()+"元");
    //将上面的cake实例对象作为AddEggCake的traget来创建AddEggCake对象。
    cake = new AddEggCake(cake);
    System.out.print("This Cake is a "+cake.getDescription()+" , ");
    System.out.println("and price is "+cake.getcost()+"元");
    cake = new AddMeatCake(cake);
    System.out.print("This Cake is a "+cake.getDescription()+" , ");
    System.out.println("and price is "+cake.getcost()+"元");

}

}

运行效果:

This Cake is a Shredded Cake , and price is 5.0元
This Cake is a agg-Shredded Cake , and price is 8.0元
This Cake is a meat-agg-Shredded Cake , and price is 13.0元
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值