装饰者模式:不改变原文件,不使用继承的情况下,动态扩展一个对象的功能
分为4个角色:(1)抽象被装饰对象 (2)具体被装饰对象:实际被动态添加功能的对象 (3)抽象装饰者(ConcreteDecorator):实现component接口,来扩展component类的功能 (4)具体装饰者:动态的添加职责的对象
实现:定义一个被装饰者的抽象接口,被装饰对象和抽象装饰者实现这个接口。在装饰类将被装饰类的对象作为成员,通过构造器为被装饰类对象赋值。在想要添加功能的方法里使用被装饰类的方法,并添加新的功能
一.理解
1. 代码示例
2. 代码
(1)抽象被装饰对象
// 男人
public interface Man {
public void getManDesc();
}
(2)被装饰对象实例
// 普通男人
public class NormalMan implements Man{
private String name = null;
public NormalMan(String name) {
this.name = name;
}
@Override
public void getManDesc() {
System.out.print(name + ": ");
}
}
(3)抽象装饰者
// 附加属性装饰者
public abstract class AttachedPropertiesDecorator implements Man{
private Man man;
public AttachedPropertiesDecorator(Man man) {
this.man = man;
}
public void getManDesc() {
man.getManDesc();
}
}
(4)装饰者实例
// 小车装饰者
public class CarDecoratorImpl extends AttachedPropertiesDecorator{
private String car = "有车";
public CarDecoratorImpl(Man man) {
super(man);
}
public void addCar() {
System.out.print(car + " ");
}
@Override
public void getManDesc() {
super.getManDesc();
addCar();
}
}
(5)客户端使用
public class DecoratorTest {
public static void main(String[] args) {
Man man = new NormalMan("张三");
Man man1 = new CarDecoratorImpl(man);
Man man2 = new HouseDecoratorImpl(man1);
Man man3 = new DepositDecoratorImpl(man2);
System.out.println("层层装饰:");
man3.getManDesc();
System.out.println();
}
}
二. 装饰者模式的应用 io流