-
装饰模式
就是动态地给一个对象添加一些额外的功能,比使用子类更为灵活。
-
适用性
1)在不影响其他对象的情况下,以动态、透明的方式给单个对象添加功能。
2)处理那些可以撤消的职责。
3)当不能使用子类的方法进行扩充时。 -
举例
例如人是要吃饭的,通过Decorator模式增加饭前洗手功能,增加饭后刷牙功能。
-
UML类图
-
代码示例
- 定义一个Person接口类,给这个接口动态的添加功能
package com.jin.demo.DesignPatterns.Decorator; /** * 定义一个Person接口类 * @auther jinsx * @date 2019-04-30 15:28 */ public interface Person { void eat(); }
- 定义一个Student,可以给这个对象添加一些功能
package com.jin.demo.DesignPatterns.Decorator; /** * 定义一个Student类实现Person类 * @auther jinsx * @date 2019-04-30 15:33 */ public class Student implements Person { @Override public void eat() { System.out.println("开始吃饭"); } }
- 维持一个指向Person对象的指针,并定义一个与Person接口一致的接口。
package com.jin.demo.DesignPatterns.Decorator; /** * @auther jinsx * @date 2019-04-30 15:36 */ public abstract class Decorator implements Person { private Person person; public Decorator(Person person) { this.person = person; } public void eat(){ person.eat(); } }
- 向组件添加功能
package com.jin.demo.DesignPatterns.Decorator; /** * @auther jinsx * @date 2019-04-30 15:43 */ public class StudentDecoratorA extends Decorator{ public StudentDecoratorA(Person person) { super(person); } @Override public void eat() { before(); super.eat(); } public void before(){ System.out.println("饭前要洗手"); } }
package com.jin.demo.DesignPatterns.Decorator; /** * @auther jinsx * @date 2019-04-30 15:47 */ public class StudentDecoratorB extends Decorator { public StudentDecoratorB(Person person) { super(person); } @Override public void eat() { super.eat(); after(); } public void after(){ System.out.println("饭后要刷牙"); } }
- 创建一个测试类
package com.jin.demo.DesignPatterns.Decorator; /** * @auther jinsx * @date 2019-04-30 15:50 */ public class TestDecorator { public static void main(String[] args) { // 正常吃饭逻辑 Person p = new Student(); // 增加洗手逻辑 p = new StudentDecoratorA(p); // 增加刷牙逻辑 p = new StudentDecoratorB(p); p.eat(); } }
- 执行测试结果
饭前要洗手 开始吃饭 饭后要刷牙
- 定义一个Person接口类,给这个接口动态的添加功能
-
点击Java之23种设计模式查看更多的设计模式
Java设计模式之装饰模式
最新推荐文章于 2025-03-06 23:30:00 发布