装饰者模式定义:动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。装饰模式是一种对象结构型模式。
1.新建food接口
package com.zheng.nie.decorator;
/**
* @author: niezheng1
* @Date: 2018/12/26 18:13
*/
public interface Food {
Float cost();
}
构建装饰类实现Food接口,确保装饰者和被装饰者是同一类型。
/**
* @author: niezheng1
* @Date: 2018/12/26 18:16
* 构件装饰类:抽象装饰类
*/
public class Decorator implements Food {
private Food food;
public Decorator(Food food) {
this.food = food;
}
@Override
public Float cost() {
return food.cost();
}
}
给煎饼果子加一个培根,继承抽象装饰类
package com.zheng.nie.decorator;
/**
* @author: niezheng1
* @Date: 2018/12/26 18:17
*/
public class Bacon extends Decorator {
public Bacon(Food food) {
super(food);
}
/**
* 增加培根花费
* @return
*/
@Override
public Float cost() {
return super.cost()+1.5f;
}
}
热狗装饰类
package com.zheng.nie.decorator;
/**
* @author: niezheng1
* @Date: 2018/12/26 18:23
*/
public class Hotdog extends Decorator{
public Hotdog(Food food) {
super(food);
}
/**
* 增加热狗花费
* @return
*/
@Override
public Float cost() {
return super.cost()+2f;
}
}
生菜装饰类
package com.zheng.nie.decorator;
/**
* @author: niezheng1
* @Date: 2018/12/26 18:25
*/
public class Lettuce extends Decorator {
public Lettuce(Food food) {
super(food);
}
/**
* 增加生菜花费
* @return
*/
@Override
public Float cost() {
return super.cost()+0.5f;
}
}
新建一个煎饼果子类,实现Food接口。
package com.zheng.nie.decorator;
/**
* @author: niezheng1
* @Date: 2018/12/26 18:15
* 煎饼果子
*/
public class PancakeFruit implements Food{
@Override
public Float cost() {
return 1f;
}
}
package com.zheng.nie.decorator;
/**
* @author: niezheng1
* @Date: 2018/12/26 18:25
*/
public class App {
public static void main(String[] args) {
Food food = new PancakeFruit();
/**用培根装饰**/
food = new Bacon(food);
/**加热狗**/
food = new Hotdog(food);
/**加生菜*/
food = new Lettuce(food);
System.out.println(food.cost());
}
}
输出如果:
5.0
类图如下
image.png
网友评论