装饰模式是为了已有功能动态的添加到对象上,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,以此需要执行特殊行为的时候,客户代码就可以在运行的时候有选择的,按顺序使用装饰类包装对象了。
定义:动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。
设计初衷:通常可以使用继承来实现功能的拓展,如果这些需要拓展的功能的种类很繁多,那么势必生成很多子类,增加系统的复杂性,同时,使用继承实现功能拓展,我们必须可预见这些拓展功能,这些功能是编译时就确定了,是静态的。
装饰模式的UML图如下
现在就举个案例使用一下装饰模式
//定义一个对象接口
interface FoodComponent{
public void process();
public void setPrice();
}
//具体被装饰对象
class malatang implements FoodComponent{
public void process() {
System.out.println("麻辣烫已经煮好了");
}
public void setPrice() {
System.out.println("麻辣烫的价格为1元");
}
}
//装饰抽象类,继承HumanComponent,从外部来扩展HumanComponent类的功能
abstract class Decorator implements FoodComponent{
FoodComponent food;
Decorator(FoodComponent food){
this.food =food;
}
public void process() {
food.process();
}
public void setPrice() {
food.setPrice();
}
}
class Decorator_one extends Decorator{
Decorator_one(FoodComponent humn) {
super(humn);
}
public void process() {
super.process();
System.out.println("麻辣烫加点辣椒");
}
public void setPrice() {
super.setPrice();
}
}
class Decorator_two extends Decorator{
Decorator_two(FoodComponent humn) {
super(humn);
}
public void process() {
super.process();
System.out.println("麻辣烫加点香菜");
}
public void setPrice() {
System.out.println("麻辣烫价格涨到2元啦");
}
}
客户端代码
public static void main(String[] args) {
FoodComponent food = new malatang();
// food.process();
//food.setPrice();
Decorator_one one = new Decorator_one(food);
// one.process();
// one.setPrice();
Decorator_two two =new Decorator_two(one);
two.process();
two.setPrice();
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/bigdata/9409.html