装点器模式(网站借鉴的)
装饰器模式(网站借鉴的)
package com.decorator; /** * 面包类 * @author Administrator * */ public class Bread extends Ingredient { private String description ; public Bread(String desc){ this.description=desc ; } public String getDescription(){ return description ; } public double getCost(){ return 2.48 ; } } package com.decorator; public class Celery extends Decorator{ public Celery(Ingredient igd){ super(igd); } public String getDescription(){ String base = ingredient.getDescription(); return base +"\n"+"Decrocated with Celery !"; } public double getCost(){ double basePrice = ingredient.getCost(); double celeryPrice =0.6; return basePrice + celeryPrice ; } } package com.decorator; public abstract class Decorator extends Ingredient { Ingredient ingredient ; public Decorator(Ingredient igd){ this.ingredient = igd; } public abstract String getDescription(); public abstract double getCost(); } package com.decorator; public class GreenGrocery extends Decorator{ public GreenGrocery (Ingredient igd){ super(igd); } public String getDescription(){ String base = ingredient.getDescription(); return base +"\n"+"Decrocated with GreenGrocery !"; } public double getCost(){ double basePrice = ingredient.getCost(); double greenGroceryPrice = 0.4; return basePrice + greenGroceryPrice ; } } package com.decorator; /** * 原料类 * @author Administrator * */ public abstract class Ingredient { public abstract String getDescription(); public abstract double getCost(); public void printDescription(){ System.out.println(" Name "+ this.getDescription()); System.out.println(" Price RMB "+ this.getCost()); } } package com.decorator; public class Mutton extends Decorator{ public Mutton(Ingredient igd){ super(igd); } public String getDescription(){ String base = ingredient.getDescription(); return base +"\n"+"Decrocated with Mutton !"; } public double getCost(){ double basePrice = ingredient.getCost(); double muttonPrice = 2.3; return basePrice + muttonPrice ; } } package com.decorator; public class Pork extends Decorator{ public Pork(Ingredient igd){ super(igd); } public String getDescription(){ String base = ingredient.getDescription(); return base +"\n"+"Decrocated with Pork !"; } public double getCost(){ double basePrice = ingredient.getCost(); double porkPrice = 1.8; return basePrice + porkPrice ; } } package com.decorator; public class DecoratorTest { public static void main(String[] args) { Ingredient compound = new Mutton(new Celery(new Bread("Master24's Bread"))); compound.printDescription(); compound = new Celery(new GreenGrocery(new Bread("Bread with milk"))); compound.printDescription(); compound = new Mutton(new Pork(new Bread("Bread with cheese"))); compound.printDescription(); } }