概述
装饰模式定义:动态地给一个对象添加额外的职责和功能。也就是说:我们可以在不使用继承、不改变原有结构的基础上扩展新的内容。举个例子,我们都担心摔碎手机屏幕,所以我们可以在手机的外表面裹一层材料(比如钢化膜,手机套)从而使得手机具有了抗摔的新功能;并且手机原本的功能(打电话,拍照,上网)并没有受到任何影响。嗯哼,看完这个小例子,我们来瞅瞅装饰模式中的四个角色:
- Component:被装饰的原始抽象(类或接口)组件
- ConcreteComponent:Component的具体实现类
- Decorator:抽象装饰者
- ConcreteDecorator:Decorator的具体实现类
以食物的例子进行代码的实现
食物有两种,炒饭和抄面,它们又可以加配菜,配菜有鸡蛋和培根。
主食Food
里面有食物名称和价格,作为父类
public class Food {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Food(String name, double price) {
this.name = name;
this.price = price;
}
public Food() {
}
}
炒饭FriedRice
继承自Food
传参
public class FriedRice extends Food {
public FriedRice() {
super("炒饭", 12);
}
}
抄面FriedNoodles
继承自Food
传参
public class FriedNoodles extends Food {
public FriedNoodles() {
super("炒面", 10);
}
}
配菜SideDish
抽象装饰者
里面有name,price,food属性,还实现了sendPropaganda宣传语,getSumPrice获得价格的方法
public abstract class SideDish {
private String name;
private double price;
private Food food;
public SideDish(String name, double price, Food food) {
this.name = name;
this.price = price;
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Food getFood() {
return food;
}
public void setFood(Food food) {
this.food = food;
}
public SideDish() {
}
public abstract String sendPropaganda();
public abstract String getSumPrice();
}
鸡蛋Egg
继承自SideDish,实现方法,并且有自己的宣传语和打折价格
public class Egg extends SideDish {
private String Propaganda="美味可口";
private double discount = 1;
public Egg( Food food) {
super("鸡蛋", 2, food);
}
@Override
public String sendPropaganda() {
return super.getName()+super.getFood().getName()+this.Propaganda;
}
@Override
public String getSumPrice() {
return super.getFood().getPrice()+super.getPrice()-this.discount+"元";
}
}
培根Bacon
继承自SideDish,实现方法,并且有自己的宣传语和打折价格
public class Bacon extends SideDish{
private String Propaganda="非常好吃";
private double discount = 0.5;
public Bacon(Food food) {
super("培根", 3, food);
}
@Override
public String sendPropaganda() {
return super.getName()+super.getFood().getName()+this.Propaganda;
}
@Override
public String getSumPrice() {
return super.getFood().getPrice()+super.getPrice()-this.discount+"元";
}
}
测试类
public class Test {
public static void main(String[] args) {
FriedRice friedRice = new FriedRice();
FriedNoodles friedNoodles = new FriedNoodles();
Egg egg = new Egg(friedRice);
Bacon bacon = new Bacon(friedNoodles);
System.out.println(egg.sendPropaganda()+" "+egg.getSumPrice());
System.out.println(bacon.sendPropaganda()+" "+bacon.getSumPrice());
}
}