概念
- 动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活;
- 多加了一层,主要是增加了函数decorate(),客户端调用的时候可以不断的装饰,而不是每一个子类都要调用函数。
// 装配到一起 public void decorate(Person component){ this.component = component; }
代码
目录结构
Client
package controller; import service.Impl.BigTrouser; import service.Impl.Tshirts; import service.Person; /** * @author SHshuo * @data 2021/10/16--8:41 * 装饰模式、比子类更加灵活(通过一层一层的装饰) */ public class Client { public static void main(String[] args) { Person p = new Person("小菜"); System.out.println("第一种装扮"); BigTrouser trouser = new BigTrouser(); Tshirts tshirts = new Tshirts(); trouser.decorate(p); tshirts.decorate(trouser); tshirts.show(); } }
抽象层
package service; /** * @author SHshuo * @data 2021/10/16--8:35 */ public class Person { private String name; public Person(){} public Person(String name){ this.name = name; } public void show(){ System.out.println("某人装扮:" + name); } }多加一层
package service; /** * @author SHshuo * @data 2021/10/16--8:36 */ public class Finery extends Person { protected Person component; // 装配到一起 public void decorate(Person component){ this.component = component; } @Override public void show() { if(component != null){ component.show(); } } }
具体实现类
package service.Impl; import service.Finery; /** * @author SHshuo * @data 2022/4/9--16:25 */ public class Tshirts extends Finery { @Override public void show() { System.out.println("T恤衫"); super.show(); } }
package service.Impl; import service.Finery; /** * @author SHshuo * @data 2022/4/9--16:25 */ public class BigTrouser extends Finery { @Override public void show() { System.out.println("垮裤"); super.show(); } }