设计模式(五)——装饰模式

[TOC]

装饰器模式

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

在装饰模式中, 必然有一个最基本、 最核心、 最原始的接口或抽象类充当 Component抽象构件。

优点

  • 装饰类和被装饰类可以独立发展,不会互相耦合。
  • 装饰器模式是继承关系的替代方案
  • 装饰器模式可以动态的扩展一个实现类的功能。

缺点

多层装饰比较复杂。尽量减少装饰类数量,以便降低系统复杂度。

代码

GitHub

定义一个接口或者一个抽象类,装饰器中最基本最核心对象。

1
2
3
4
public interface Component {

void method();
}

定义具体构件,Component的实现,被装饰类

1
2
3
4
5
6
public class ConcreteComponent implements Component {
@Override
public void method() {
System.out.println("原来的方法");
}
}

定义装饰角色,实现接口或抽象方法,属性里有一个private变量指向Component抽象构件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public abstract class Decorator implements Component{

private Component component;

public Decorator(Component component){
super();
this.component = component;
}

@Override
public void method() {
component.method();
}
}

Decorator类并不是必须的。

具体的装饰类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class ConcreteDecorator1 extends Decorator {

public ConcreteDecorator1(Component component){
super(component);
}

public void method1(){
System.out.println("装饰器1装饰");
}

@Override
public void method(){
System.out.println("增加装饰1包装");
super.method();
System.out.println("装饰1包装结束");
}
}


public class ConcreteDecorator2 extends Decorator {

public ConcreteDecorator2(Component component){
super(component);
}

public void method2(){
System.out.println("装饰器2装饰");
}

@Override
public void method(){
System.out.println("增加装饰2包装");
super.method();
System.out.println("装饰2包装结束");
}
}

main方法测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static void main(String[] args){

//原来对象
Component component = new ConcreteComponent();
component.method();

System.out.println("-------------------------");
//被装饰1修饰
ConcreteDecorator1 component1 = new ConcreteDecorator1(component);
component1.method1();
component1.method();
System.out.println("-------------------------");
//被装饰2修饰
ConcreteDecorator2 component2 = new ConcreteDecorator2(component);
component2.method2();
component2.method();
System.out.println("-------------------------");
//多重装饰
Component component3 = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
component3.method();
System.out.println("-------------------------");
Component component4 = new ConcreteDecorator1(new ConcreteDecorator2(new ConcreteComponent()));
component4.method();


}

测试结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
原来的方法
-------------------------
装饰器1装饰
增加装饰1包装
原来的方法
装饰1包装结束
-------------------------
装饰器2装饰
增加装饰2包装
原来的方法
装饰2包装结束
-------------------------
增加装饰2包装
增加装饰1包装
原来的方法
装饰1包装结束
装饰2包装结束
-------------------------
增加装饰1包装
增加装饰2包装
原来的方法
装饰2包装结束
装饰1包装结束

装饰器模式使用场景

  • 需要扩展一个类的功能,或给一个类增加附加功能;
  • 动态的给一个对象增加附加功能,这些功能可以再动态的撤销;
  • 为一批兄弟类进行改装或增加功能。
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
显示 Gitment 评论