装饰者模式定义
装饰者模式动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更有弹性,装饰者模式也体现了开闭原则(ocp);
咖啡案例
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:03
*/
public abstract class Drink
{
public String desc;
private float price = 0.0f;
public String getDesc()
{
return desc;
}
public void setDesc(String desc)
{
this.desc = desc;
}
public float getPrice()
{
return price;
}
public void setPrice(float price)
{
this.price = price;
}
//计算费用的抽象方法
public abstract float cost();
}
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:05
*/
public class Coffee extends Drink
{
@Override
public float cost()
{
return super.getPrice();
}
}
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:07
*/
public class YDLCoffee extends Coffee
{
//只能在构造方法里面 继承抽象类的属性给抽象类赋值 因为构造方法是初始化当前类的
public YDLCoffee()
{
setDesc("意大利咖啡");
setPrice(6.0f);
}
}
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:12
*/
public class USCoffee extends Coffee
{
public USCoffee()
{
setDesc("美式咖啡");
setPrice(5.0f);
}
}
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:14
*/
public class CHNCoffee extends Coffee
{
public CHNCoffee()
{
setDesc("中国咖啡!");
setPrice(7.0f);
}
}
开始准备装饰者
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:15
*/
public class Decorator extends Drink
{
private Drink obj;
public Decorator(Drink obj)
{
this.obj = obj;
}
@Override
public float cost()
{
return super.getPrice()+obj.cost();
}
@Override
public String getDesc()
{
return super.getDesc()+" "+super.getPrice()+"&&"+obj.getDesc();
}
}
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:21
*/
public class Chocolate extends Decorator
{
public Chocolate(Drink obj)
{
super(obj);
setDesc("巧克力");
setPrice(2.0f);
}
}
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:22
*/
public class Milk extends Decorator
{
public Milk(Drink obj)
{
super(obj);
setDesc("牛奶");
setPrice(2.0f);
}
}
package com.lesson9.decorator;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2020/8/31 9:23
*/
public class Soy extends Decorator
{
public Soy(Drink obj)
{
super(obj);
setDesc("豆浆");
setPrice(1.5f);
}
}
形象的来看装饰者模式有点像一层裹着一层,一层又一层的继承,然后装饰者和被装饰者分开
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/16435.html