例子一、咖啡的制作
/** * 饮料类 */ public abstract class Beverage { //描述 String description = "Unknown Beverage"; public String getDescription(){ return description; } //价格 public abstract double cost(); }
/** * 调料类 */ public abstract class CondimentDecorator extends Beverage{ //所有的调料装饰者都必须重新实现该方法 public abstract String getDescription(); }
/** * 浓咖啡,是一种饮料 */ public class Espresso extends Beverage{ public Espresso(){ description = "Espresso"; } @Override public double cost() { return 1.99; } }
/** * 混合咖啡 */ public class HouseBlend extends Beverage{ public HouseBlend(){ description = "House Blend Coffee"; } @Override public double cost() { return 0.89; } }
/** * 摩卡,一种调料 */ public class Mocha extends CondimentDecorator{ Beverage beverage; public Mocha(Beverage beverage){ this.beverage = beverage; } @Override public String getDescription() { return beverage.getDescription() + ",Mocha"; } @Override public double cost() { return 0.20 + beverage.cost(); } }
/** * 星巴克咖啡的制作 */ public class StarbuzzCoffee { public static void main(String[] args) { Beverage beverage1 = new Espresso();//浓咖啡,不需要调料 System.out.println(beverage1.getDescription() + " $" + beverage1.cost()); Beverage beverage2 = new HouseBlend();//混合咖啡,需要调料 beverage2 = new Mocha(beverage2); System.out.println(beverage2.getDescription() + " $" + beverage2.cost()); } /** * 运行结果: * Espresso $1.99 House Blend Coffee,Mocha $1.09 */ }
例子二、io流的装饰
import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * 编写自己的java IO装饰者 * 把流内的所有大写字符转成小写 * FilterInputStream 包含其他一些输入流,它将这些流用作其基本数据源, * 它可以直接传输数据或提供一些额外的功能。FilterInputStream 类本身只 * 是简单地重写那些将所有请求传递给所包含输入流的 InputStream 的所有方法。 */ public class LowerCaseInputStream extends FilterInputStream{ /** * @param in */ protected LowerCaseInputStream(InputStream in) { super(in); } //重写,转化为小写 @Override public int read() throws IOException { int c = super.read(); return (c == -1 ? c : Character.toLowerCase((char)c)); } //重写,转化为小写 @Override public int read(byte[] b, int off, int len) throws IOException { int result = super.read(b, off, len); for(int i = off; i < off + result; i++){ b[i] = (byte)Character.toLowerCase((char)b[i]); } return result; } }
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * 测试java IO装饰者 */ public class TestLowerCaseInStr { public static void main(String[] args) throws IOException { int c; InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("C:\\Format.txt"))); while((c = in.read()) >= 0){ System.out.println((char)c); } in.close(); } }