public interface Cake { public int cost(); }
<!-- 装饰蛋糕 --> public abstract class CakeDecorator implements Cake{ }
public class AppleCake extends CakeDecorator{ private Cake cake; public AppleCake(Cake cake) { this.cake = cake; } @Override public int cost() { System.out.println("送小蛋糕"); return cake.cost() + 12; } }
public class MilkCake implements Cake{ @Override public int cost() { return 100; } }
测试
public class Test { public static void main(String[] args) { MilkCake mc = new MilkCake(); AppleCake ac = new AppleCake(mc); OrangeCake oc = new OrangeCake(ac); //OrangeCake oc = new OrangeCake(new AppleCake(new MilkCake())); System.out.println(oc.cost()); } }
===============================================================
===============================================================
<!-- 举例 -->
OutputStream
ByteArrayOutputStream
FileOutputStream
PipedOutputStream
FilterOutputStream
BufferedOutputStream
DataOutputStream
------------------------------------
装饰者模式
继承属于扩展形式之一,但不见得是弹性最好的最佳方式
在我们的设计中,应该允许行为可以被扩展,而无需修改现有的代
码(开闭原则)
除了继承,使用装饰者模式也可以让我们扩展行为
装饰者可以在被装饰者的行为前面、后面加上自己的行为,甚至可
以将被装饰者的行为取代,而达到特定的目的
装饰者模式会导致设计中出现许多小对象,如果过度使用,会让程
序变得复杂
时间: 2024-11-13 07:54:36