学习笔记之装饰者模式

装饰者(Decorator)模式又名包装(Wrapper)模式,它动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
[code]
package org.kangsg219.abst;

//星巴兹咖啡抽象类
public abstract class Beverage {

public String description="Unknown Beverage!";

public String getDescription(){
return description;
}

public abstract double cost();

}

[/code]
[code]
package org.kangsg219.abst;

//调料(Condiment)抽象类
public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();

}

[/code]
[code]
package org.kangsg219.impl;

import org.kangsg219.abst.Beverage;

//浓缩咖啡(Espresso)具体类
public class Espresso extends Beverage {

public Espresso(){
description="Espresso";
}

@Override
public double cost() {

return 1.99;
}

}

[/code]
[code]
package org.kangsg219.impl;

import org.kangsg219.abst.Beverage;
//HouseBlend咖啡具体类
public class HouseBlend extends Beverage {

public HouseBlend(){
description="HouseBlend";
}

@Override
public double cost() {

return 0.89;
}

}

[/code]
[code]
package org.kangsg219.impl;

import org.kangsg219.abst.Beverage;
import org.kangsg219.abst.CondimentDecorator;

public class Mocha extends CondimentDecorator {

public Beverage beverage;

public Mocha(Beverage beverage){
this.beverage=beverage;
}

@Override
public String getDescription() {

return beverage.getDescription()+",mocha";
}

@Override
public double cost() {

return beverage.cost()+0.20;
}

}

[/code]
[code]
package org.kangsg219.impl;

import org.kangsg219.abst.Beverage;
import org.kangsg219.abst.CondimentDecorator;

//奶泡具体装饰类
public class Whip extends CondimentDecorator {

public Beverage beverage;

public Whip(Beverage beverage){
this.beverage=beverage;
}

@Override
public String getDescription() {

return beverage.getDescription()+",Whip";
}

@Override
public double cost() {

return beverage.cost()+ 0.10;
}

}

[/code]
[code]
package org.kangsg219.test;

import org.kangsg219.abst.Beverage;
import org.kangsg219.impl.Espresso;
import org.kangsg219.impl.HouseBlend;
import org.kangsg219.impl.Mocha;
import org.kangsg219.impl.Whip;

public class StarbuzzCoffee {


public static void main(String[] args) {
//仅要一杯浓缩咖啡,不要调料。
Beverage beverage=new Espresso();
System.out.println(beverage.getDescription()+" $"+beverage.cost());

//双倍摩卡的HouseBlend咖啡
Beverage beverage2=new HouseBlend();
beverage2=new Mocha(beverage2);
beverage2=new Mocha(beverage2);
beverage2=new Whip(beverage2);
System.out.println(beverage2.getDescription()+" $"+beverage2.cost());
}

}

[/code]
运行结果:
Espresso $1.99
HouseBlend,mocha,mocha,Whip $1.39
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值