装饰器模式:动态地给一个对象添加一些额外地职责,就增加功能来说,装饰器比子类更加灵活
优点:在原对象基础上额外增加功能,而不影响原对象
实现:咖啡店里售卖咖啡,加糖和加奶都需要额外收费,有的可以选择加糖,有的客人选择加奶,有的客人则选择原味。其实不管是加糖还是加奶,都是在原咖啡地基础上增加额外属性。
1、抽象产品
/*** 抽象产品-咖啡*/public abstract class Coffee {/*** 获取咖啡名称*/public abstract String getName();/*** 获取咖啡价格*/public abstract Double getPrice();}
2、实际产品
/*** 实际产品-蓝山咖啡*/public class LanShanCoffee extends Coffee{/*** 获取咖啡名称*/public String getName(){return "蓝山咖啡";}/*** 获取咖啡价格*/public Double getPrice(){return 8.0;}}/*** 实际产品-猫屎咖啡*/public class MaoShiCoffee extends Coffee{/*** 获取咖啡名称*/public String getName(){return "猫屎咖啡";}/*** 获取咖啡价格*/public Double getPrice(){return 9.2;}}
3、抽象装饰器类
/*** 装饰器类*/public abstract class Decorator extends Coffee{Coffee coffee;/*** 设置装饰类*/public Decorator(Coffee coffee){this.coffee = coffee;}/*** 获取咖啡名称*/public abstract String getName();/*** 获取咖啡价格*/public abstract Double getPrice();}
4、装饰器类实现
/*** 牛奶-装饰器*/public class MilkDecorator extends Decorator{public MilkDecorator(Coffee coffee){super(coffee);}/*** 获取咖啡名称*/public String getName(){return coffee.getName()+",加牛奶";}/*** 获取咖啡价格*/public Double getPrice(){return coffee.getPrice()+1.5;}}/*** 糖-装饰器*/public class SugarDecorator extends Decorator{public SugarDecorator(Coffee coffee){super(coffee);}/*** 获取咖啡名称*/public String getName(){return coffee.getName()+",加糖";}/*** 获取咖啡价格*/public Double getPrice(){return coffee.getPrice()+0.2;}}
5、测试
/*** 测试装饰器模式*/public class TestDecorator {public static void main(String [] args){Coffee coffee = new LanShanCoffee();coffee = new MilkDecorator(coffee);coffee = new SugarDecorator(coffee);System.out.println(coffee.getName());System.out.println(coffee.getPrice());Coffee coffee1 = new MaoShiCoffee();coffee1 = new MilkDecorator(coffee1);System.out.println(coffee1.getName());System.out.println(coffee1.getPrice());}}
测试结果:
