//InputStream提供的基本方法(Component)
public abstract class InputStream implements Closeable {
}
//默认目标实现类(ConcreteComponent)
public class FileInputStream extends InputStream {
}
/*装饰实现类(FilterInputStream)一定是继承或实现原始接口(InputStream)的,内部有包含一个原始接口的超类(其实就是某个默认目标实现类)*/
//Decorator
public class FilterInputStream extends InputStream {
/**
* The input stream to be filtered.
*/
protected volatile InputStream in;
protected FilterInputStream(InputStream in) {
this.in = in;
}
}
//具体装饰类(ConcreteDecorator)
public class BufferedInputStream extends FilterInputStream {
public BufferedInputStream(InputStream in) {
this(in, DEFAULT_BUFFER_SIZE);
}
}
//具体装饰类(ConcreteDecorator)
public class DataInputStream extends FilterInputStream implements DataInput {
public DataInputStream(InputStream in) {
super(in);
}
}
package com.qbz.test;
interface ICoffee {
void showCoffee();
float showPrice();
}
// 原始咖啡
class Coffee implements ICoffee {
private String name;
private float price;
public Coffee(String name, float price) {
this.name = name;
this.price = price;
}
@Override
public void showCoffee() {
System.out.println(name + " coffee");
}
@Override
public float showPrice() {
return price;
}
}
// 抽象装饰器
abstract class Decorator implements ICoffee {
private ICoffee coffee;
public void setCoffee(ICoffee coffee) {
this.coffee = coffee;
}
@Override
public void showCoffee() {
coffee.showCoffee();
}
@Override
public float showPrice() {
return coffee.showPrice();
}
}
// 加糖咖啡
class Sugar extends Decorator {
@Override
public void showCoffee() {
System.out.println("加糖");
super.showCoffee();
}
@Override
public float showPrice() {
return super.showPrice() + 5;
}
}
// 加牛奶的咖啡
class SugarMilk extends Decorator {
@Override
public void showCoffee() {
System.out.println("加糖、加牛奶");
super.showCoffee();
}
@Override
public float showPrice() {
return super.showPrice() + 10;
}
}
public class Main {
public static void main(String[] args) {
Coffee coffee = new Coffee("拿铁", 20);
// 加糖
Decorator sugar = new Sugar();
sugar.setCoffee(coffee);
sugar.showCoffee();
System.out.println(sugar.showPrice());
// 加糖,加牛奶的咖啡
Decorator sugarmilk = new SugarMilk();
sugarmilk.setCoffee(coffee);
sugarmilk.showCoffee();
System.out.println(sugarmilk.showPrice());
}
}
加糖
拿铁 coffee
25.0
加糖、加牛奶
拿铁 coffee
30.0