装饰者设计模式:在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。
通过创建一个包装对象来实现
典型应用:IO流的包装
代码示例:
package test.test1;
/**
* 米饭,抽象父类
*
* @author Sy
*
*/
public interface Rice {
// 价格
public float price();
// 描述
public String discription();
}
package test.test1;
/**
* 配菜(装饰)
*
* @author Sy
*
*/
public abstract class Jardiniere implements Rice {
// 强关联
private Rice rice;
public Jardiniere(Rice rice) {
this.rice = rice;
}
public float price() {
return rice.price();
}
public String discription() {
return rice.discription();
}
}
package test.test1;
/**
* 粗米
*
* @author Sy
*
*/
public class CoarseRice implements Rice {
public float price() {
return 1.5f;
}
public String discription() {
return "米饭";
}
}
package test.test1;
/**
* 荤菜装饰实体
*
* @author Sy
*
*/
public class Meat extends Jardiniere {
public Meat(Rice rice) {
super(rice);
}
public float price() {
return super.price() + 3.0f;
}
public String discription() {
return super.discription() + "+荤菜";
}
}
package test.test1;
/**
* 蔬菜装饰实体
*
* @author Sy
*
*/
public class Vegetable extends Jardiniere {
public Vegetable(Rice rice) {
super(rice);
}
public float price() {
return super.price() + 1.5f;
}
public String discription() {
return super.discription() + "+素菜";
}
}
public class Test {
public static void main(String[] args) {
// 有人买饭
CoarseRice cr = new CoarseRice();
Meat meat = new Meat(cr);
Vegetable veg = new Vegetable(meat);
veg.discription();
veg.price();
System.out.println("你所要的是:" + veg.discription());
System.out.println("价钱为:" + veg.price() + "元");
}
}