GOF23设计模式(八)

GOF设计模式之装饰模式(decorator)与外观模式(Facade)

装饰模式(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
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
68
/**
* 抽象组件
*
*/
public interface ICar {
void move();
}
//ConcreteComponent 具体构件角色(真实对象)
class Car implements ICar{

@Override
public void move() {
System.out.println("在陆地上跑");
}
}
//Decorator 装饰角色
class SuperCar implements ICar{
protected ICar car;
public SuperCar(ICar car) {
this.car = car;
}
@Override
public void move() {
car.move();
}
}
//ConcreteDecorator 具体装饰角色
class FlyCar extends SuperCar{
public FlyCar(ICar car) {
super(car);
}
public void fly() {
System.out.println("在天上飞");
}
@Override
public void move() {
super.move();
fly();
}
}
class WaterCar extends SuperCar{

public WaterCar(ICar car) {
super(car);
}
public void swim() {
System.out.println("在水上漂");
}
@Override
public void move() {
super.move();
swim();
}
}
class AiCar extends SuperCar{

public AiCar(ICar car) {
super(car);
}
public void automove() {
System.out.println("自动驾驶");
}
@Override
public void move() {
super.move();
automove();
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ublic class Client {

public static void main(String[] args) {
Car car=new Car();
car.move();
FlyCar flycar=new FlyCar(car);
System.out.println("---添加功能---");
flycar.move();
WaterCar watercar=new WaterCar(flycar);
System.out.println("---添加功能---");
watercar.move();;
System.out.println("---拥有功能---");
AiCar aicar=new AiCar(new FlyCar(new WaterCar(car)));
aicar.move();
}
}

结果

在陆地上跑
—添加功能—
在陆地上跑
在天上飞
—添加功能—
在陆地上跑
在天上飞
在水上漂
—拥有功能—
在陆地上跑
在水上漂
在天上飞
自动驾驶

外观模式(Facade)

这个模式经常在编程中使用,不管你听没听过这个名字,此模式就是对用户隐藏程序运行细节,只提供一个接口就可以实现。

代码(代码来自博客)

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
//https://blog.csdn.net/u012361379/article/details/88820428  码农日常
public class FacadeTest {

public static void main(String[] args) {
Facade f = new Facade();
f.method();
}
}

//外观角色
class Facade {
private SubSystem01 obj1 = new SubSystem01();
private SubSystem02 obj2 = new SubSystem02();
private SubSystem03 obj3 = new SubSystem03();

public void method() {
obj1.method1();
obj2.method2();
obj3.method3();
}
}

//子系统角色
class SubSystem01 {
public void method1() {
System.out.println("子系统01的method1()被调用!");
}
}

//子系统角色
class SubSystem02 {
public void method2() {
System.out.println("子系统02的method2()被调用!");
}
}

//子系统角色
class SubSystem03 {
public void method3() {
System.out.println("子系统03的method3()被调用!");
}
}

结果

子系统01的method1()被调用!
子系统02的method2()被调用!
子系统03的method3()被调用!

原创技术分享,您的支持将鼓励我继续创作
0%