设计模式之装饰者模式

先来看一个例子:
如果我们读取文件内容往往都会使用
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("c:\\a.txt"));

上大学的时候老师告诉我们这个叫流,在FileInputStream上面又套了一个更大的管道,其实这是使用了装饰者模式,在不改变底层代码的情况下,给对象赋予新的功能。
现在通过一个实例来展示装饰者模式,我们知道coca-cola有多种饮品,比如CocaCola和Sprite,它们的包装又分为大瓶、中瓶、小瓶,使用装饰者模式就可以快速的知道拿在手上的饮品的种类和价格。
public abstract class Drinking {
	String description = "unknow";
	public String getDescription(){
		return description;
	}
	public abstract double cost();
}

public class CocaCola extends Drinking{
	
	
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 1.0;
	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return "Coca-Cola";
	}
}

public class Sprite extends Drinking{

	
	@Override
	public double cost() {
		// TODO Auto-generated method stub
		return 1.0;
	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return "Sprite";
	}
}

public class BigBottle extends Drinking{

	Drinking btl;
	public BigBottle(Drinking btl){
		this.btl = btl;
		description = "this is a big bottle";
	}
	@Override
	public double cost() {
		return 1.5 + btl.cost();
	}
	
	public String getDescription(){
		return btl.getDescription()+description;
	}
}


public class MiddleBottle extends Drinking{

	Drinking btl;
	public MiddleBottle(Drinking btl){
		this.btl = btl;
		description = "this is a middle bottle";
	}
	@Override
	public double cost() {
		return 1.5 + btl.cost();
	}
	
	public String getDescription(){
		return btl.getDescription()+description;
	}
}

public class NormalBottle extends Drinking{

	Drinking btl;
	public NormalBottle(Drinking btl){
		this.btl = btl;
		description = "this is a normal bottle";
	}
	@Override
	public double cost() {
		return 1.5 + btl.cost();
	}
	
	public String getDescription(){
		return btl.getDescription()+description;
	}
}

public class TestMain {
	public static void main(String[] args){
		Drinking coca = new CocaCola();
		coca = new BigBottle(coca);
		System.out.println(coca.getDescription());
		System.out.println(coca.cost());
	}
}

你可能感兴趣的:(装饰者模式)