# 装饰者模式
# 简介
结构型模式,通过对真实对象的一层又一层包装,可以给对象添加很多额外的功能,调用起来感觉很复杂。
# 示例
public interface Componet {
void doSomeThing();
}
public class ConcreteComponet implements Componet{
@Override
public void doSomeThing() {
System.out.println("do some thing");
}
}
public class SayHiDecorator implements Componet{
private Componet componet;
public SayHiDecorator(Componet componet){
this.componet = componet;
}
@Override
public void doSomeThing() {
System.out.println("Hi!");
componet.doSomeThing();
}
}
public class SayThanksDecorator implements Componet{
private Componet componet;
public SayThanksDecorator(Componet componet){
this.componet = componet;
}
@Override
public void doSomeThing() {
componet.doSomeThing();
System.out.println("Thanks!");
}
}
# 调用
@Test
public void tt(){
Componet componet = new SayThanksDecorator(new SayHiDecorator(new ConcreteComponet()));
componet.doSomeThing();
}
控制台打印:
Hi!
do some thing
Thanks!