设计模式 - 装饰者模式
设计模式 - 装饰者模式
构造型模式:这些设计模式关注类和对象的组合。继承的观念被用来组合接口和定义组合对象获得新功能的方式
装饰器模式:允许向一个现有的对象添加新功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的包装
我的理解,想用个栗子来说明
一幅画(可以是油画、水墨画等)始终是幅画
用画框裱起来
用瓶子装起来
这里的 画框 瓶子 就是充当的装饰器
这里的画是独立的没有 画框、瓶子还是画
画框、瓶子也可以不装饰画也还是画框、瓶子
但是用装饰器装饰后在画的表现上添加了新的特点
优点:装饰类和被装饰类可以独立发展,不会相互耦合,这种模式可以替代继承
缺点:多层装饰 增加 整体的复杂
使用场景:
1. 拓展一个类的功能
2. 动态添加、撤销 功能
下面是一个关于装饰模式的代码demo

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68public class Decorator {
public static void main(String[] args) {
Shape circle = new Circle();
RedShapeDecorator redShapeDecorator = new RedShapeDecorator(circle);
circle.draw();
System.out.println("---------------------------------");
redShapeDecorator.draw();
System.out.println("#########################################");
Rectangle rectangle = new Rectangle();
RedShapeDecorator redShapeDecorator1 = new RedShapeDecorator(rectangle);
rectangle.draw();
System.out.println("-------------------------");
redShapeDecorator1.draw();
}
}
class RedShapeDecorator extends AbstractShapeDecorator {
public RedShapeDecorator(Shape decoratorShape) {
super(decoratorShape);
}
@Override
public void draw() {
decoratorShape.draw();
// 装饰器的精髓一步
setRedBorder(decoratorShape);
}
private void setRedBorder(Shape decoratorShape) {
System.out.println("Border Color: Red");
}
}
abstract class AbstractShapeDecorator implements Shape {
protected Shape decoratorShape;
public AbstractShapeDecorator(Shape decoratorShape) {
this.decoratorShape = decoratorShape;
}
@Override
public void draw() {
decoratorShape.draw();
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape - Circle");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape - Rectangle");
}
}
interface Shape {
void draw();
}
- 本文作者:Jun
- 本文链接:http://mambajun.github.io/2019/12/13/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E8%A3%85%E9%A5%B0%E8%80%85%E6%A8%A1%E5%BC%8F/index.html
- 版权声明:本博客所有文章均采用 BY-NC-SA 许可协议,转载请注明出处!