标签:and system pos 模式 参考 抽象类 end http xtend
一、定义
动态的给对象添加一些额外的属性或行为。相比于使用继承,装饰者模式更加灵活。
1 public abstract class Sweet { 2 String description = "Sweet"; 3 4 public String getDescription() { 5 return description; 6 } 7 8 public abstract double cost(); 9 }
定义被装饰者蛋糕类,Cake .java
1 public class Cake extends Sweet { 2 @Override 3 public String getDescription() { 4 return "一个蛋糕"; 5 } 6 7 @Override 8 public double cost() { 9 return 66; 10 } 11 }
定义抽象装饰者类Decorator.java
1 public abstract class Decorator extends Sweet { 2 public abstract String getDescription(); 3 }
定义具体装饰者水果类,FruitDecorator.java
1 public class FruitDecorator extends Decorator { 2 Sweet sweet; 3 4 public FruitDecorator(Sweet sweet) { 5 this.sweet = sweet; 6 } 7 8 @Override 9 public String getDescription() { 10 return sweet.getDescription() + ",水果"; 11 } 12 13 @Override 14 public double cost() { 15 return sweet.cost() + 10; 16 } 17 }
定义具体装饰者蜡烛类,CandleDecorator.java
1 public class CandleDecorator extends Decorator { 2 Sweet sweet; 3 4 public CandleDecorator(Sweet sweet) { 5 this.sweet = sweet; 6 } 7 8 @Override 9 public String getDescription() { 10 return sweet.getDescription() + ",蜡烛"; 11 } 12 13 @Override 14 public double cost() { 15 return sweet.cost() + 10; 16 } 17 }
最后根据不同的选择来结算价格
1 public static void main(String[] args) { 2 3 Cake cake = new Cake(); 4 System.out.println(cake.getDescription() + "总共花费" + cake.cost()); 5 6 FruitDecorator fruitDecorator = new FruitDecorator(cake); 7 System.out.println(fruitDecorator.getDescription() + "总共花费" + fruitDecorator.cost()); 8 9 CandleDecorator candleDecorator = new CandleDecorator(fruitDecorator); 10 System.out.println(candleDecorator.getDescription() + "总共花费" + candleDecorator.cost()); 11 12 }
参考:
https://juejin.im/post/5a33e7d76fb9a045167d412c
标签:and system pos 模式 参考 抽象类 end http xtend
原文地址:https://www.cnblogs.com/wylwyl/p/10496480.html