装饰器模式属于结构型模式
这种模式创建了一个装饰类,
向一个现有的对象添加新的功能,同时又不改变其结构,
装饰器模式和代理模式很像,
代理模式中被访问对象是由代理类创建,
而装饰器模式中被访问对象是由访问者传入的。
包含抽象角色、具体角色、抽象装饰类、具体装饰类四个角色。
抽象角色
package com.example.duohoob.dp.decorator;
/**
* 抽象角色-玩具
* @Title: Toy.java
* @Package com.example.duohoob.dp.decorator
*
* @author yangwei
* @date 2022年7月10日
*/
public interface Toy {
/**
* 特征
* @author yangwei
* @date 2022年7月10日
*
*/
void notes();
}
具体角色
package com.example.duohoob.dp.decorator;
/**
* 具体角色-玩具小汽车,实现抽象角色
* @Title: Car.java
* @Package com.example.duohoob.dp.decorator
*
* @author yangwei
* @date 2022年7月10日
*/
public class Car implements Toy {
@Override
public void notes() {
// TODO Auto-generated method stub
System.out.println("一个玩具小汽车");
}
}
抽象装饰类
package com.example.duohoob.dp.decorator;
/**
* 抽象装饰类,实现抽象角色
* @Title: Decorator.java
* @Package com.example.duohoob.dp.decorator
*
* @author yangwei
* @date 2022年7月10日
*/
public abstract class Decorator implements Toy {
protected Toy toy; // 不能用private修饰,会导致子类访问不到
public Decorator(Toy toy) {
super();
this.toy = toy;
}
@Override
public void notes() {
// TODO Auto-generated method stub
toy.notes();
}
}
具体装饰类
package com.example.duohoob.dp.decorator;
/**
* 具体装饰类-颜色装饰类,继承抽象装饰类
* @Title: ColorDecorator.java
* @Package com.example.duohoob.dp.decorator
*
* @author yangwei
* @date 2022年7月10日
*/
public class ColorDecorator extends Decorator {
public ColorDecorator(Toy toy) {
super(toy);
// TODO Auto-generated constructor stub
}
@Override
public void notes() {
// TODO Auto-generated method stub
toy.notes(); // 这里的toy是父类的变量
decorator(); // 装饰
}
/**
* 具体装饰方法,加颜色
* @author yangwei
* @date 2022年7月10日
*
*/
private void decorator() {
System.out.println("它的颜色是红的");
}
}
测试
package com.example.duohoob.dp.decorator;
public class Test {
public static void main(String[] args) {
Toy car = new Car(); // 玩具小汽车
ColorDecorator cd = new ColorDecorator(car); // 装饰器
cd.notes();
}
}
运行