装饰模式的思想
装饰模式,顾名思义,就像房间装修房间,在已有的房间中添加各种东西,与现实生活中不太一样的是,我们装修房间是把配件拿到房间里装修,但是在java中,我们是装修的配件持有房间。其实就类似于我们在每个配件上标识上它应该装修在哪个房间里。
代码实现,我们以食物的主菜和配菜为例:
如下,定义了一个食物类
public class Food {
private String name;
private double price;
public Food() {
}
public Food(String name, double price) {
this.name = name;
this.price = 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 class FireRice extends Food{
public FireRice(){
super("炒饭",10.0);
}
}
配菜抽象类:
配菜类中我们有个Food类型的属性,这就是它要配的主菜
/*
@author Nian
@Date 2022/8/11 10:55
@purpose
@Note
*/
public abstract class SideDish {
private String name;
private double price;
private Food food; //配菜类持有一个Food类型的属性
public SideDish() {
}
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 abstract double sumPrice();
public abstract void desc();
}
配菜类的子类,鸡蛋类:
/*
@author Nian
@Date 2022/8/11 11:03
@purpose
@Note
*/
public class Egg extends SideDish{
//配菜必须配着主菜,所以这里只有有参构造
public Egg(Food food){
super("鸡蛋",2.0,food);
}
private int discount = 1;
public double sumPrice(){
return this.getFood().getPrice()+this.getPrice()-discount;
}
public void desc(){
System.out.println(this.getName()+this.getFood().getName()+sumPrice()+"元");
}
}
测试类:
/*
@author Nian
@Date 2022/8/11 10:55
@purpose
@Note
*/
public class Test {
public static void main(String[] args) {
FireRice fireRice = new FireRice();
Egg egg = new Egg(fireNoodles); //将现有的Food类添加到Egg配菜类
egg.desc();
}
}
结果:
其实我们装饰模式在我们熟知的IO流中也使用到了,我们构造一个缓冲的输入输出流的时候,需要一个输入输出流来构造,不能无参构造。