装饰者模式[decorator]
应用一:
StarBuzz咖啡店有很多饮料,每种饮料都可以根据客户需要加一些调料,比如深培咖啡可以加摩卡(或双倍摩卡),
而且某些饮料可以分为大中小杯,根据容量不同,售价不同,而且调料的价格根据饮料的容量不同而不同
(比如大杯咖啡加糖要1元,中杯咖啡加糖要0.9元等)
设计原则:
对扩展开放,对修改关闭(本例中各种饮料都有共同的大中小杯特性--这是关闭的部分,
另外各种具体子类饮料和调料的描述和价格都不相同--这是开放的部分)
http://dl.iteye.com/upload/attachment/404935/12d0b120-8d0d-3769-a3ab-c37fa6eeca4a.jpg
public class SuarbuzzCoffee {public static void main(String[] args) {// 订一杯中杯的浓咖啡Beverage espresso = new Espresso(Beverage.GRANDE);System.out.println(espresso.getDescription() + " $" + espresso.cost());// 订一杯大杯的普通咖啡Beverage houseBlend = new HouseBlend(Beverage.VENTI);houseBlend.setSize(300);// 在普通咖啡中加入(调料),包括两份摩卡和一份奶泡houseBlend = new Mocha(houseBlend);houseBlend = new Mocha(houseBlend);houseBlend = new Whip(houseBlend);System.out.println(houseBlend.getDescription() + " $" + houseBlend.cost());}} 应用二:
使用InputStream读取文件时候,将字母都转换为小写字母。
public class LowerCaseInputStream extends FilterInputStream {public LowerCaseInputStream(InputStream in) {super(in);}public int read() throws IOException {int c = super.read();return (c == -1) ? c : Character.toLowerCase((char)c);}public int read(byte[] b, int offset, int len) throws IOException {int result = super.read(b, offset, len);for (int i = offset; i < offset + result; i++) {b = (byte)Character.toLowerCase((char)b);}return result;}}
public class InputTest {public static void main(String[] args) {int c;try {InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("test.txt")));while((c = in.read()) >= 0) {System.out.print((char)c);}} catch (Exception e) {e.printStackTrace();}}}
页:
[1]