装饰模式(Decorator)

Posted by Jfson on 2018-06-22

装饰器模式,Decorator模式允许您通过将对象包装在装饰器类的对象中来动态更改对象在运行时的行为。

用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

使用场景: 1、扩展一个类的功能。 2、动态增加功能,动态撤销。

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
37
38
//创建一个接口:
public interface Shape {
void draw();
}
//创建实现接口的实体类。
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
//装饰类
public class RedShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape){
System.out.println("Border Color: Red");
}
}

pv UV: