0、设计模式分类

  • 创建型模式

    用于描述”怎样创建对象”,它的主要特点是”将对象的创建与使用分离”。GoF(四人组)书中提供了单例、原型、工厂方法、抽象工厂、建造者等5种创建型模式。

  • 结构型模式

    用于描述如何将类或对象按某种布局组成更大的结构,GoF(四人组)书中提供了代理、适配器、桥接、装饰、外观、享元、组合等7种结构型模式。

  • 行为型模式

    用于描述类或对象之间怎样相互协作共同完成单个对象无法单独完成的任务,以及怎样分配职责。GoF(四人组)书中提供了模板方法、策略、命令、职责链、状态、观察者、中介者、迭代器、访问者、备忘录、解释器等11种行为型模式。


在软件开放中,为了提高软件系统的可维护性和可复用性,增加软件的可扩展性和灵活性,程序员要尽量根据7条原则来开发程序,从而提高软件开发效率、节约软件开发成本和维护成本。

1、单一职责原则

【1】基本介绍

对类来说的,即一个类应该只负责一项职责。如类A负责两个不同职责:职责1,职责2。当职责1需求变更而改变A时,可能造成职责2执行错误,所以需要将类A的粒度分解为A1,A2。

【2】以交通工具案例讲解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 单一职责案例1

// 交通工具类
// 1、存在问题:违反单一职责原则,飞机不能在公路上跑
// 2、解决方法:根据交通工具运行方法不同,分解成不同类即可
class Vehicle {
public void run(String vehicle) {
System.out.println(vehicle + " 在公路上行驶。。。");
}

public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.run("摩托车");
vehicle.run("汽车");
vehicle.run("飞机");
}
}
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
// 方案2
// 对上述案例1进行修改

// 方案2分析
// 1、遵守单一职责原则
// 2、但是这样做的改动很大,即将类分解,同时修改客户端
// 3、改进:直接修改Vehicle类,改动的代码会比较少
class RoadVehicle {
public void run(String vehicle) {
System.out.println(vehicle + "公路运行");
}
}

class AirVehicle {
public void run(String vehicle) {
System.out.println(vehicle + "天空运行");
}
}

class WaterVehicle {
public void run(String vehicle) {
System.out.println(vehicle + "水中运行");
}
}

class SingleResponsibility {
RoadVehicle rv = new RoadVehicle();
rv.run();

AirVehicle av = new RoadVehicle();
av.run();

// ......
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 方案3
// 1、这种修改方法没有对原来的类做大的修改,只是增加了方法
// 2、这里虽然没有在类这个级别上遵守单一职责原则,但是在方法级别上仍然遵守单一职责原则
class Vehicle {
public void runRoad(String vehicle) {
System.out.println(vehicle + "在公路上运行...")
}

public void runAir(String vehicle) {
System.out.println(vehicle + "在天空上运行...")
}

public void runWater(String vehicle) {
System.out.println(vehicle + "在水中运行...")
}

public static void main(String[] args) {
Vehicle v = new Vehicle();
v.runRoad("汽车");
v.runWater("轮船");
v.runAir("飞机");
}
}
【3】单一职责原则注意事项和细节
  1. 降低类的复杂度,一个类只负责一项职责。
  2. 提高类的可读性,可维护性。
  3. 降低变更引起的风险。
  4. 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级别违反单一职责原则;只有类中方法数量足够少,可以在方法级别保持单一职责原则。


2、接口隔离原则

【1】基本介绍

客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上。

image-20230315105236168

类A通过接口Interface1依赖类B,类C通过接口Interface1依赖类D,如果接口Interface1对于类A和类C来说不是最小接口,那么类B和类D必须去实现他们不需要的方法。

按隔离原则应当这样处理:将接口Interface1拆分为独立的几个接口,类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。


【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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
// 接口隔离

interface Interface1 {
void operation1();
void operation2();
void operation3();
void operation4();
void operation5();
}

class B implements Interface1 {
public void operation1() {
System.out.println("B 实现了 operation1");
}

public void operation2() {
System.out.println("B 实现了 operation2");
}

public void operation3() {
System.out.println("B 实现了 operation3");
}

public void operation4() {
System.out.println("B 实现了 operation4");
}

public void operation5() {
System.out.println("B 实现了 operation5");
}
}

class D implements Interface1 {
public void operation1() {
System.out.println("D 实现了 operation1");
}

public void operation2() {
System.out.println("D 实现了 operation2");
}

public void operation3() {
System.out.println("D 实现了 operation3");
}

public void operation4() {
System.out.println("D 实现了 operation4");
}

public void operation5() {
System.out.println("D 实现了 operation5");
}
}

class A { // A类通过接口Interface1依赖(使用)B类,但是只会用到1,2,3方法
public void depend1(Interface1 i) {
i.operation1();
}

public void depend2(Interface1 i) {
i.operation2();
}

public void depend3(Interface1 i) {
i.operation3();
}
}

class C { // C类通过接口Interface1依赖(使用)D类,但是只会用到1,4,5方法
public void depend1(Interface1 i) {
i.operation1();
}

public void depend4(Interface1 i) {
i.operation4();
}

public void depend5(Interface1 i) {
i.operation5();
}
}
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// 使用接口隔离原则对上述代码进行改进

// 1、类A通过接口Interface1依赖B,类C通过接口Interface1依赖D,如果接口Interface1对于类A和类C来说不是最小接口,那么类B和D必须去实现他们不需要的方法
// 2、将接口Interface1拆分为独立的几个接口,类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。
// 3、接口Interface1中出现的方法,根据实际情况拆分为三个接口。

// 接口1
interface Interface1 {
void operation1();
}
// 接口2
interface Interface2 {
void operation2();
void operation3();
}
// 接口3
interface Interface3 {
void operation4();
void operation5();
}

class B implements Interface1, Interface2 {
public void operation1() {
System.out.println("B 实现了 operation1");
}

public void operation2() {
System.out.println("B 实现了 operation2");
}

public void operation3() {
System.out.println("B 实现了 operation3");
}
}

class D implements Interface1, Interface3 {
public void operation1() {
System.out.println("D 实现了 operation1");
}

public void operation4() {
System.out.println("D 实现了 operation4");
}

public void operation5() {
System.out.println("D 实现了 operation5");
}
}

class A { //A 类通过接口Interface1,Interface2依赖(使用)B类,但是只会用到1、2、3方法
public void depend1(Interface1 i) {
i.operation1();
}
public void depend2(Interface2 i) {
i.operation2();
}
public void depend3(Interface2 i) {
i.operation3();
}
}

class C { //C类通过接口Interface1,Interface3 依赖(使用)D类,但是只会用到1、4、5方法
public void depend1(Interface1 i) {
i.operation1();
}
public void depend4(Interface3 i) {
i.operation4();
}
public void depend5(Interface3 i) {
i.operation5();
}
}

public class Segregation {
// 使用一把
A a = new A();
a.depend1(new B()); // A类通过接口去依赖B类
a.depend2(new B());
a.depend3(new B());

C c = new C();
c.depend1(new D()); // C类通过接口去依赖(使用)D类
c.depend4(new D());
c.depend5(new D());
}

3、依赖倒转原则

【1】基本介绍

依赖倒转原则(Dependence Inversion Principle)是指:

1)高层模块不应该依赖低层模块,二者都应该依赖其抽象。

2)抽象不应该依赖细节,细节应该依赖抽象。

3)依赖倒转(倒置)的中心思想是面向接口编程。

4)依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类。

5)使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成。


【2】代码展示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 完成Person接收消息的功能
// 方式1完成
// 1、简单,比较容易想到
// 2、如果我们获取的对象是微信,短信等等,则新增类。同时Persons也要增加相应的接收方法。
// 3、解决思路:引入一个抽象的接口IReceiver,表示接收者,这样Person类与接口发生依赖。
// 因为Email,WeiXin等等属于接收的范围,他们各自实现IReceiver接口就ok,
// 这样我们就复合依赖倒转原则。
class Person {
public void receive(Email email) {
System.out.println(email.getInfo());
}
}

class Email {
public String getInfo() {
return "电子邮件信息:hello,world";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 修改,使用依赖倒转原则
interface IReceiver {
String getInfo();
}

class Email implements IReceiver {
public String getInfo() {
return "";
}
}

class WeiXin implements IReceiver {
public String getInfo() {
return "";
}
}

class Person {
public void receive(IReceiver rec) {
System.out.println(rec.getInfo());
}
}

依赖传递的三种方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 方式1:通过接口传递实现依赖
// 开关的接口
interface IOpenAndClose {
void open(ITV tv); // 抽象方法,接收接口
}

interface ITV { //ITV接口
void play();
}

// 实现接口
class OpenAndClose implements IOpenAndClose {
public void open(ITV tv) {
tv.play();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 方式2:通过构造方法依赖传递
interface IOpenAndClose {
void open(); // 抽象方法
}

interface ITV { // ITV接口
void play();
}

class OpenAndClose implements IOpenAndClose {
public ITV tv;
public OpenAndClose(ITV tv) {
this.tv = tv;
}
public void open() {
this.tv.play();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 方式3:通过setter方法传递
interface IOpenAndClose {
void open(); // 抽象方法
void setTv(ITV tv);
}

interface ITV { // ITV接口
void play();
}

class OpenAndClose implements IOpenAndClose {
private ITV tv;

public void setTv(ITV tv) {
this.tv = tv;
}

public void open() {
this.tv.play();
}
}

【3】依赖倒转注意事项和细节

1)低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好。

2)变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化。

3)继承时遵循里氏替换原则。


4、里氏替换原则

【1】OO中继承性的思考和说明

1)继承包含这样一层含义:父类中凡是已经实现好的方法,实际上是在设定规范和契约,虽然它不强制要求所有的子类必须遵循这些契约,但是如果子类对这些已经实现的方法任意修改,就会对整个继承体系造成破坏。

2)继承在给程序设计带来便利的同时,也带来了弊端,比如使用继承会给程序带来侵入性,程序的可移植性降低,增加对象间的耦合性,如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都可能产生故障。

3)问题提出:在编程中,如何正确的使用继承?=> 里氏替换原则


【2】基本介绍

1)里氏替换原则(Liskov Substitution Principle)在1988年,由麻省理工学院的一位姓里的女士提出的。

2)如果对每个类型为T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。换句话说,所有引用基类的地方必须能透明地使用其子类的对象。通俗来讲:任何基类可以出现的地方,子类一定可以出现。即子类可以扩展父类的功能,但不能改变父类原有的功能。即子类继承父类时,除添加新的方法完成新增功能外,尽量不要重写父类的方法。 如果通过重写父类的方法来完成新的功能,这样写起来虽然简单,但是整个继承体系的可复用性会比较差,特别是运用多态比较频繁时,程序运行出错的概率会非常大。

3)在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类的方法。

4)里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题。


【3】思考代码
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
// 看程序思考问题和解决思路
class A {
public int func1(int num1, int num2) {
return num1 - num2;
}
}

class B extends A {
public int func1(int a, int b) {
return a + b;
}

public int func2(int a, int b) {
return func1(a, b) + 9;
}
}

class Test {
public static void main(String[] args) {
A a = new A();
System.out.println("11-3=" + a.func1(11, 3));
System.out.println("1-8=" + a.func1(1, 8));

System.out.println("-----------------------");
B b = new B();
System.out.prinln("11-3=" + b.func1(11, 3)); // 这里本意氏求11-3
System.out.prinln("1-8=" + b.func1(1, 8));
System.out.prinln("11+3+9=" + b.func2(11, 3));
}
}
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
// 使用里氏替换原则对上述代码进行改进

// 创建一个更加基础的基类
class Base {
// 把更加基础的方法和成员写到Base类
}

// A类
class A extends Base {
// 返回两个数的差
public int func1(int num1, int num2) {
return num1 - num2;
}
}

// B类
class B extends Base {
// 如果B需要使用A类的方法,使用组合关系
private A a = new A();

// 我们仍然想使用A的方法
public int func3(int a, int b) {
return this.a.func1(a, b);
}
}
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
69
70
71
/* 正方形不是长方形

在数学领域里,正方形毫无疑问是长方形,它是一个长宽相等的长方形。所以,我们开发的一个与几何图形相关的软件系统,就可以顺理成章的让正方形继承自长方形。

*/
public class Rectangle {
private double length;
private double width;

public void setLength(double length) {
this.length = length;
}
public double getLength() {
return length;
}

public void setWidth(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
}

public class Square extends Rectangle {
@Override
public void setLenth(double length) {
super.setLength(length);
super.setWidth(length);
}

@Override
public void setWidth(double width) {
super.setLength(width);
super.setWidth(width);
}
}

public class RectangleDemo {
public static void resize(Rectangle rectangle) {
// 判断宽如果比长小,进行扩宽的操作
while(rectangle.getWidth() <= rectangle.getLenth()) {
rectangle.setWidth(rectangle.getWidth() + 1);
}
}
public void printLengthAndWidth(Rectangle rectangle) {
System.out.println(rectangle.getLenth());
System.out.println(rectangle.getWidth());
}

public static void main(String[] args) {
Rectangle r = new Rectangle();
r.setWidth(10);
r.setLength(20);
resize(r);
printLengthAndWidth(r);

// 创建正方形
Square s = new Square();
s.setLenth(10);
resize(s);
printLengthAndWidth(s);
}
}

/*
我们运行一下这段代码就会发现,假如我们把一个普通长方形作为参数传入resize方法,就会看到长方形宽度逐渐增长的效果,当宽度大于长度,代码就会停止,这种行为的结果符合我们的预期。

假如我们再把一个正方形作为参数传入resize方法后,就会看到正方形的宽度和长度都在不断增长,代码会一直运行下去,直至系统产生溢出错误。所以,普通的长方形是适合这段代码的,正方形不适合。
我们得出结论:在resize方法中,Rectangle类型的参数是不能被Square类型的参数所代替,如果进行了替换就得不到预期结果。因此,Square类和Rectangle类之间的继承关系违反了里氏代换原则,它们之间的继承关系不成立,正方形不是长方形。
*/
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
69
70
71
/*
如何改进?此时我们需要重新设计它们之间的关系,抽象出来一个四边形接口(Quadrilateral),让Rectangle类和Square类实现Quadrilateral接口。
*/
public interface Quadrilateral {
double getLength();
double getWidth();
}


public class Rectangle implements Quadrilateral {
private double length;
private double width;

public void setLength(double length) {
this.length = length;
}
public double getLength() {
return length;
}

public void setWidth(double width) {
this.width = width;
}
public double getWidth() {
return width;
}
}

public class Square implements Quadrilateral {
private double side;

public void setSide(double side) {
this.side = side;
}
public double getSide() {
return side;
}

public double getLength() {
return side;
}
public double getWidth() {
return side;
}
}

public class RectangleDemo {
public static void resize(Rectangle rectangle) {
// 判断宽如果比长小,进行扩宽的操作
while(rectangle.getWidth() <= rectangle.getLenth()) {
rectangle.setWidth(rectangle.getWidth() + 1);
}
}
public void printLengthAndWidth(Quadrilateral quadrilateral) {
System.out.println(quadrilateral.getLenth());
System.out.println(quadrilateral.getWidth());
}

public static void main(String[] args) {
Rectangle r = new Rectangle();
r.setWidth(10);
r.setLength(20);
resize(r);
printLengthAndWidth(r);

// 创建正方形
Square s = new Square();
s.setLenth(10);
printLengthAndWidth(s);
}
}

5、开闭原则

【1】基本介绍

1)开闭原则(Open Closed Principle)是编程中最基础、最重要的设计原则。

2)一个软件实体如类,模块和函数应该对扩展开放,对修改关闭。用抽象构建框架,用实现扩展细节。

3)当软件需要变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。

4)编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则。

要想达到这样的效果,我们需要使用接口和抽象类。

因为抽象灵活性好,适应性广,只要抽象的合理,可以基本保持软件架构的稳定。而软件中易变的细节可以从抽象派生来的实现类来进行扩展,当软件需要发生变化时,只需要根据需求重新派生一个实现类来扩展就可以了。


【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
// 阅读以下代码,分析问题

// 缺点:违反了设计模式的ocp原则,即对扩展开放,对修改关闭。即当我们给类增加新功能的时候,尽量不修改代码,或者尽可能少修改代码。
// 比如我们这时候要新增加一个图形种类,我们需要做如下修改,修改的地方较多。比如,修改GraphicEditor、再加一个三角形类。

class GraphicEditor {
public void drawShape(Shape s) {
if(s.m_type == 1) {
drawRectangle(s);
}else if(s.m_type == 2) {
drawCircle(s);
}
}

public void drawRectangle(Shape r) {
System.out.println("矩形");
}

public void drawCircle(Shape r) {
System.out.println("圆形");
}
}

class Shape {
int m_type;
}

class Rectangle extends Shape {
Rectangle() {
super.m_type = 1;
}
}

class Circle extends Shape {
Circle() {
super.m_type = 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
// 改进思路:把创建Shape类做成抽象类,并提供一个抽象的draw方法,让子类去实现即可,这样我们有新的图形种类时,只需要让新的图形类继承Shape,并实现draw方法即可,使用方的代码就不需要修改,满足了开闭原则。

// 优化后的代码
abstract class Shape {
public abstract void drawShape();
}

class Rectangle extends Shape {
public void drawShape(){
System.out.println("长方形");
}
}

class Circle extends Shape {
public void drawShape(){
System.out.println("圆形");
}
}

class GraphicEditor {
public void drawShape(Shape shape) {
shape.drawShape();
}
}
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
/* 搜狗输入法皮肤设计。

分析:搜狗输入法的皮肤是输入法背景图片、窗口颜色和声音等元素的组合。用户可以根据自己的喜爱更换自己的输入法的皮肤,也可以从网上下载新的皮肤。这些皮肤有共同的特点,可以为其定义一个抽象类(AbstractSkin),而每个具体的皮肤(DefaultSpecificSkin和HeimaSpecificSkin)是其子类。用户窗体可以更具需要选择或者增加新的主题,而不需要修改原代码,所以它是满足开闭原则的。

*/
public abstract class AbstractSkin {
public abstract void display();
}

public class DefaultSpecificSkin extends AbstractSkin {
public void display() {
System.out.println("默认皮肤");
}
}

public class HeimaSpecificSkin extends AbstractSkin {
public void display() {
System.out.println("黑马皮肤");
}
}

public class SouGouInput {
private AbstractSkin skin;
public SouGouInput(AbstractSkin skin) {
this.skin = skin;
}

public void display() {
skin.display();
}
}

6、迪米特法则

【1】基本介绍

1)一个对象应该对其他对象保持最少的了解。

2)类与类关系越密切,耦合度越大。

3)迪米特法则(Demeter Principle)又叫最少知道原则,即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public方法,不对外泄漏任何信息。

4)迪米特法则还有个更简单的定义:只与直接的朋友通信。

5)直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称成员变量、方法参数、方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接的朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。


【2】代码案例

1)有一个学校,下属有各个学院和总部,现在要求打印出学校总部员工ID和学院员工ID。

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
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
69
70
71
72
73
74
75
76
77
78
79
80
// 客户端
public class Demeter {
public static void main(String[] args) {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}
}

// 学校总部员工
class Employee {
private String id;

public void setId(String id) {
this.id = id;
}

public String getId() {
return id;
}
}

// 学院员工类
class CollegeEmployee {
private String id;

public void setId(String id) {
this.id = id;
}

public String getId() {
return this.id;
}
}

// 管理学院员工的管理类
class CollegeManager {
// 返回学院的所有员工
public List<CollegeEmployee> getAllEmployee() {
List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
for (int i = 0; i < 10; i++) { // 增加10个员工到list
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学院员工id=" + i);
list.add(emp);
}
return list;
}
}

// 学校管理类
class SchoolManager {
// 返回学校总部员工
public List<Employee> getAllEmployee() {
List<Employee> list = new ArrayList<Employee>();

for (int i = 0; i < 5; i++) {
Employee emp = new Employee();
emp.setId("学校总部员工id=" + i);
list.add(emp);
}

return list;
}

// 该方法完成输出学校总部和学院员工信息(id)
void printAllEmployee(CollegeManager sub) {
List<CollegeEmployee> list1 = sub.getAllEmployee();
System.out.println("-------------分公司员工-------------");
for (CollegeEmployee e : list1) {
System.out.println(e.getId());
}
List<Employee> list2 = this.getAllEmployee();
System.out.println("-------------学校总部员工-------------");
for (Employee e : list2) {
System.out.println(e.getId());
}
}
}

// 分析SchoolManager类的直接朋友类有哪些:Employee、CollegeManager
// CollegeEmployee不是直接朋友,这样违背了迪米特法则。
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
// 改进代码

class CollegeManager {
// 返回学院的所有员工
public List<CollegeEmployee> getAllEmployee() {
List<CollegeEmployee> list = new ArrayList<CollegeEmployee>();
for (int i = 0; i < 10; i++) { // 增加10个员工到list
CollegeEmployee emp = new CollegeEmployee();
emp.setId("学院员工id=" + i);
list.add(emp);
}
return list;
}

// 输出学院员工的信息
public void printEmployee() {
List<CollegeEmployee> list1 = getAllEmployee();
System.out.println("-------------学院员工-------------");
for (CollegeEmployee e : list1) {
System.out.println(e.getId());
}
}
}

// 学校管理类
class SchoolManager {
// 返回学校总部员工
public List<Employee> getAllEmployee() {
List<Employee> list = new ArrayList<Employee>();
for (int i = 0; i < 5; i++) {
Employee emp = new Employee();
emp.setId("学校总部员工id=" + i);
list.add(emp);
}
return list;
}

// 该方法完成输出学校总部和学院员工信息(id)
void printAllEmployee(CollegeManager sub) {
sub.printEmployee(); // 将输出学院的员工方法,封装到CollegeManager

List<Employee> list2 = this.getAllEmployee();
System.out.println("-------------学校总部员工-------------");
for (Employee e : list2) {
System.out.println(e.getId());
}
}
}

【3】迪米特法则注意事项和细节

1)迪米特法则的核心是降低类之间的耦合。

2)但是注意:由于每个类都减少了不必要的依赖,因此迪米特法则只是要求降低类间(对象间)耦合关系,并不是要求完全没有依赖关系。


7、合成复用原则(Composite Reuse Principle)

【1】基本介绍

原则是尽量使用合成/聚合的方式,而不是使用继承。

image-20230316151140076


【2】继承复用缺点和组合复用优点

1)继承复用破坏了类的封装性。因为继承会将父类的实现细节暴露给子类,父类对子类是透明的,所以这种复用又称为”白箱”复用。

2)子类与父类的耦合度高。父类的实现的任何改变都会导致子类的实现发生变化,这不利于类的扩展与维护。

3)它限制了复用的灵活性。从父类继承而来的实现是静态的,在编译时已经定义,所以在运行时不可能发生变化。

采用组合或聚合复用时,可以将已有对象纳入新对象中,使之称为新对象的一部分,新对象可以调用已有对象的功能,它有着以下优点:

1)它维持了类的封装性。因为成员对象的内部细节是新对象看不见的,所以这种复用又称为”黑箱”复用。

2)对象间的耦合度低。可以在类的成员位置声明抽象。

3)复用的灵活性高,这种复用可以在运行时动态进行,新对象可以动态地引用与成员对象类型相同的对象。(可传递该类或该成员的子类对象)


【3】汽车父类管理程序示例

汽车按”动力源”可划分为汽油汽车、电动汽车等。按”颜色”划分可分为白色汽车、黑色汽车和红色汽车等。如果同时考虑这两种分类,其组合就很多。类图如下:

image-20230613011647853

从上面类图可以看到使用继承复用产生了很多子类,如果现在又有新的动力源或者新的颜色的话就需要定义新的类。试着改成聚合复用。

image-20230613011916914


【4】设计原则核心思想

1)找出应用中可能需要变化之处,把他们独立出来,不要和那些不需要变化的代码混在一起。

2)针对接口编程,而不是针对实现编程。

3)为了交互对象之间的松耦合设计而努力。