1 package 装饰模式; 2 3 public interface IBread { 4 5 public void prepair(); 6 7 public void kneadFlour(); 8 9 public void steamed(); 10 11 public void process(); 12 }
1 package 装饰模式; 2 3 public class NormalBread implements IBread{ 4 5 @Override 6 public void prepair() { 7 8 System.out.println("准备面粉,水以及发酵粉..."); 9 } 10 11 @Override 12 public void kneadFlour() { 13 14 System.out.println("和面..."); 15 } 16 17 @Override 18 public void steamed() { 19 20 System.out.println("蒸馒头...香喷喷的馒头出炉了"); 21 } 22 23 @Override 24 public void process() { 25 26 prepair(); 27 kneadFlour(); 28 steamed(); 29 } 30 31 }
1 package 装饰模式; 2 3 public abstract class AbstractBread implements IBread { 4 5 private final IBread bread; 6 7 public AbstractBread(IBread bread) { 8 super(); 9 this.bread = bread; 10 } 11 @Override 12 public void prepair() { 13 this.bread.prepair(); 14 } 15 @Override 16 public void kneadFlour() { 17 this.bread.kneadFlour(); 18 } 19 @Override 20 public void steamed() { 21 this.bread.steamed(); 22 } 23 24 @Override 25 public void process() { 26 prepair(); 27 kneadFlour(); 28 steamed(); 29 } 30 31 }
1 package 装饰模式; 2 3 public class CornDecorator extends AbstractBread{ 4 5 public CornDecorator(IBread bread) { 6 7 super(bread); 8 } 9 10 public void paint(){ 11 12 System.out.println("添加柠檬黄的着色剂"); 13 } 14 @Override 15 public void kneadFlour() { 16 //添加着色剂后和面 17 this.paint(); 18 super.kneadFlour(); 19 } 20 21 22 }
1 package 装饰模式; 2 3 public class SweetDecorator extends AbstractBread { 4 5 public SweetDecorator(IBread bread) { 6 7 super(bread); 8 } 9 10 public void paint(){ 11 12 System.out.println("添加甜蜜素..."); 13 } 14 15 @Override 16 public void kneadFlour() { 17 //添加甜蜜素后和面 18 this.paint(); 19 super.kneadFlour(); 20 } 21 22 }
1 package 装饰模式; 2 3 public class Client { 4 5 public static void main(String[] args) { 6 7 System.out.println("=======开始装饰馒头"); 8 IBread normalBread = new NormalBread(); 9 normalBread = new SweetDecorator(normalBread); 10 normalBread = new CornDecorator(normalBread); 11 normalBread.process(); 12 System.out.println("=======装饰馒头结束"); 13 } 14 }
1 =======开始装饰馒头 2 准备面粉,水以及发酵粉... 3 添加柠檬黄的着色剂 4 添加甜蜜素... 5 和面... 6 蒸馒头...香喷喷的馒头出炉了 7 =======装饰馒头结束