设计模式系列文章
设计模式(一):创建型之单例模式
设计模式(二、三):创建型之工厂方法和抽象工厂模式
设计模式(四):创建型之原型模式
设计模式(五):创建型之建造者模式
设计模式(六):结构型之代理模式
设计模式(七):结构型之适配器模式
设计模式(八):结构型之装饰器模式
5 种创建型模式
7 种结构型模式
11 种行为型模式
我们先来看一个快餐店的例子
计算总价
就会显得比较麻烦传统方式:
使用继承的方式存在的问题:
装饰者模式定义
指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式
装饰(Decorator)模式中的角色:
代码如下:
@Data
@AllArgsConstructor
public abstract class FastFood {
private float price;//价格
private String desc; //描述
public abstract float cost();//获取价格
}
//炒饭
public class FriedRice extends FastFood {
public FriedRice() {
super(10, "炒饭");
}
@Override
public float cost() {
return getPrice();
}
}
//炒面
public class FriedNoodles extends FastFood {
public FriedNoodles() {
super(12, "炒面");
}
@Override
public float cost() {
return getPrice();
}
}
聚合
进来@Data
public abstract class Garnish extends FastFood {
//声明快餐类的变量
private FastFood fastFood;
public Garnish(FastFood fastFood,float price, String desc) {
super(price, desc);
this.fastFood = fastFood;
}
}
//鸡蛋配料
public class Egg extends Garnish {
public Egg(FastFood fastFood) {
super(fastFood,1,"鸡蛋");
}
@Override
public float cost() {
return getPrice() + getFastFood().getPrice();
}
@Override
public String getDesc() {
return super.getDesc() + getFastFood().getDesc();
}
}
//培根配料
public class Bacon extends Garnish {
public Bacon(FastFood fastFood) {
super(fastFood,2,"培根");
}
@Override
public float cost() {
return getPrice() + getFastFood().getPrice();
}
@Override
public String getDesc() {
return super.getDesc() + getFastFood().getDesc();
}
}
public class Client {
public static void main(String[] args) {
//点一份炒饭
FastFood food = new FriedRice();
System.out.println(food.getDesc() + " " + food.cost() + "元");
System.out.println("===============");
//在上面的炒饭中加一个鸡蛋
food = new Egg(food);
System.out.println(food.getDesc() + " " + food.cost() + "元");
System.out.println("================");
//再加一个鸡蛋
food = new Egg(food);
System.out.println(food.getDesc() + " " + food.cost() + "元");
System.out.println("================");
food = new Bacon(food);
System.out.println(food.getDesc() + " " + food.cost() + "元");
}
}
以BufferedWriter举例来说明
public class Demo {
public static void main(String[] args) throws Exception{
//创建BufferedWriter对象
//创建FileWriter对象
FileWriter fw = new FileWriter("C:\\Users\\Think\\Desktop\\a.txt");
BufferedWriter bw = new BufferedWriter(fw);
//写数据
bw.write("hello Buffered");
bw.close();
}
}
使用起来感觉确实像是装饰者模式,接下来看它们的结构:
小结:
BufferedWriter使用装饰者模式对Writer子实现类进行了增强,添加了缓冲区,提高了写数据的效率
相同点
增强目标方法
不同点