读书笔记—Head First 设计模式— 装饰者模式
装饰者模式(Decorator Pattern)
装饰者模式——动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
所谓装饰者模式,包含两个对象,一个为装饰者,一个为被装饰者。装饰者、被装饰者拥有相同的父类,装饰者通过构造函数获取被装饰者的对象并在被装饰者的基础上重新修饰它,再将自己赋给需要的用户。利用此模式层层包含以达到多级修饰的效果。
好,下面上代码。
import java.util.ArrayList;
abstract class Food {
ArrayList<String> fdName;
ArrayList<String> getfdDescription() {
return fdName;
}
abstract double cast();
}
abstract class supplementaryFood extends Food{
abstract ArrayList<String> getfdDescription();
}
class Rice extends Food {
public Rice() {
// TODO Auto-generated constructor stub
ArrayList<String> a = new ArrayList<String>();
a.add("Rice");
this.fdName = a;
}
@Override
double cast() {
// TODO Auto-generated method stub
return 1;
}
}
class Eggs extends supplementaryFood {
Food food;
Eggs(Food food){
this.food = food;
}
@Override
ArrayList<String> getfdDescription() {
// TODO Auto-generated method stub
this.fdName = food.getfdDescription();
this.fdName.add("eggs");
return this.fdName;
}
@Override
double cast() {
return 2 + food.cast();
// TODO Auto-generated method stub
}
}
public class Decorator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Food myFood;
myFood = new Rice();
System.out.println(myFood.getfdDescription()+" "+myFood.cast());
myFood = new Eggs(myFood);
System.out.println(myFood.getfdDescription()+" "+myFood.cast());
}
}
我设计了一个共同的父类Food类,并设计了它的子类抽象类副食类(supplementaryFood)通过利用特有的副食类型来修饰Food类型的食物,我设计的例子不是一个特别好的例子,纯粹是为了展示装饰者模式的用法。
其中有一点要说的是,我将他们食物的名字用一个ArrayList存放,虽然我这次写的类中并没有特别去展现它的意思,这主要是为了在之后的使用中方便去管理食物的名字,检测是否有重复可以变成Double,如果要改变输出格式也会更方便一些。
我这次所写的装饰者模式在真正的使用中会存在两个问题,一是设计类时如何分类,二是大量的小类如何管理。我认为如果我来用的话肯定不会单纯的只用装饰者模式而是与其他模式相结合的使用。
我在设计模式这方面还很年轻,如果以后有新的理解会返回来及时更新滴。
附上类图一副。