装饰模式Decorator

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11409608.html

 

1. 定义
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式比生成子类更为灵活。

 

2. 结构图

Component:组件对象的接口,可以给这些对象动态地添加职责。
ConcreteComponent:具体的组件对象,实现组件对象接口,通常就是被装饰器装饰的原始对象,也就是可以给这个对象添加职责。
Decorator:所有装饰器的抽象父类,需要定义一个与组件接口一致的接口,并持有一个Component对象,其实就是持有一个被装饰的对象。注意这个被装饰的对象不一定是最原始的那个对象,也可能是被其他装饰器装饰过后的对象,反正都是实现的同一个接口,也就是同一类型。
ConcreteDecorator:实际的装饰器对象,实现具体要向被装饰器对象添加的功能。

 

3. 本质
装饰模式的本质:动态组合。

 

4. Code Demo

Component.java

1 package org.fool.dp.decorator;
2 
3 public interface Component {
4     void doSomething();
5 }

ConcreteComponent.java

1 package org.fool.dp.decorator;
2 
3 public class ConcreteComponent implements Component {
4     @Override
5     public void doSomething() {
6         System.out.println("function A");
7     }
8 }

Decorator.java

 1 package org.fool.dp.decorator;
 2 
 3 public class Decorator implements Component {
 4     private Component component;
 5 
 6     public Decorator(Component component) {
 7         this.component = component;
 8     }
 9 
10     @Override
11     public void doSomething() {
12         component.doSomething();
13     }
14 }

ConcreteDecorator1.java

 1 package org.fool.dp.decorator;
 2 
 3 public class ConcreteDecorator1 extends Decorator {
 4     public ConcreteDecorator1(Component component) {
 5         super(component);
 6     }
 7 
 8     @Override
 9     public void doSomething() {
10         super.doSomething();
11 
12         doAnotherThing();
13     }
14 
15     private void doAnotherThing() {
16         System.out.println("function B");
17     }
18 }

ConcreteDecorator2.java

 1 package org.fool.dp.decorator;
 2 
 3 public class ConcreteDecorator2 extends Decorator {
 4     public ConcreteDecorator2(Component component) {
 5         super(component);
 6     }
 7 
 8     @Override
 9     public void doSomething() {
10         super.doSomething();
11 
12         doAnotherThing();
13     }
14 
15     private void doAnotherThing() {
16         System.out.println("function C");
17     }
18 }

Client.java

1 package org.fool.dp.decorator;
2 
3 public class Client {
4     public static void main(String[] args) {
5         Component component = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
6 
7         component.doSomething();
8     }
9 }

 

posted @ 2019-08-25 22:03  李白与酒  阅读(178)  评论(0编辑  收藏  举报