《Head First Design Patterns》装饰者模式学习练习:
装饰者模式我们常见的Demo:文件读写io时候,会有InputStream,FileInputStreat,BufferedInputStream的使用。常见的
FileInputStream fileInputStream=new FileInputStream(string);
BufferedInputSream bufferedInputStream=new BufferedInputStream(fileInputStream);
装饰者模式定义:动态地将责任附加到对象上,若要扩展功能,修饰者提供了比继承更有弹性的替代方案。
新增设计原则:
类应对扩展开放,对修改关闭(即 开放-关闭原则)
以选蛋糕为例,可能会有草莓味,巧克力味,或者巧克力草莓味的,那么定义蛋糕的时候就需用到装饰者模式,以方便后期添加其他口味。
蛋糕抽象类:
public abstract class Cake {
protected String description = "Cake";
public String getDescrip(){
return description;
}
}
甜味蛋糕具体类:
public class SweetCake extends Cake{
public SweetCake(){
description = "sweet cake";
}
}
蛋糕修饰类:
public abstract class CakeDecorater extends Cake{
public abstract String getDescrip();
}
草莓蛋糕:
public class Strawberry extends CakeDecorater{
private Cake cake;
public Strawberry(Cake cake){
this.cake = cake;
}
@Override
public String getDescrip() {
// TODO Auto-generated method stub
return " strawberry " + cake.getDescrip();
}
public String getTaste(){
return "strawberry";
}
}
巧克力蛋糕:
public class Chocolate extends CakeDecorater{
private Cake cake;
public Chocolate(Cake cake){
this.cake = cake;
}
@Override
public String getDescrip() {
// TODO Auto-generated method stub
return " chocalate " + cake.getDescrip();
}
public String getTaste(){
return "chocalate";
}
}
public class TestDecorater {
public static void main(String[] args){
Cake cake = new SweetCake();
Cake choCake = new Chocolate(cake);
System.out.println(choCake.getDescrip());
Cake strawCake = new Strawberry(choCake);
System.out.println(strawCake.getDescrip());
}
}
测试结果: