余一

纸上得来终觉浅,绝知此事要躬行。

0%

七大设计原则 设计模式学习(一)

设计模式的目的:

编写软件过程中,程序员面临着来自 耦合性,内聚性以及可维护性,可扩展性,重用性,灵活性 等多方面的挑战。设计模式是为了让程序具有更好的:

  1. 代码重用性
  2. 可读性
  3. 可扩展性
  4. 可靠性
  5. 是程序呈现高内聚,低耦合的特性

七大设计原则:

  1. 单一职责原则
  2. 接口隔离原则
  3. 依赖倒转(倒置)原则
  4. 里氏替换原则
  5. 开闭原则
  6. 迪米特法则
  7. 合成复用原则

1.单一职责原则

基本介绍:

对类来说,即一个类应该只负责一项职责,如果A类负责两个不同的职责:职责1,指责2。

当职责1需求变更而改变A类时,可能造成职责2执行错误。所以需要将A类的粒度分解为A1,A2。

注意事项与细节:

  1. 降低类的复杂度,一个类只负责一项职责。
  2. 提高类的可读性,可维护性
  3. 降低变更引起的风险
  4. 通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单一职责原则;只有类中方法足够少,可以在方法级别保持单一职责原则。

2.接口隔离原则

基本介绍:

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

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

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

如图所示,当A类通过接口Interface1依赖(使用)B类,但只会用到operation1,2,3方法;C类通过接口Interface1依赖(使用)D类,但只会用到operation1,4,5方法。

代码示例:

Interface1:

1
2
3
4
5
6
7
interface Interface1{
void operation1();
void operation2();
void operation3();
void operation4();
void operation5();
}

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
class B implements Interface1{

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

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

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

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

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

D类:

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
class D implements Interface1{

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

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

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

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

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

A类:

1
2
3
4
5
6
7
8
9
10
11
12
13
class A{//A类通过接口Interface1依赖(使用)B类,但只会用到operation1,2,3方法
void depend1(Interface1 i){
i.operation1();
}

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

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

C类:

1
2
3
4
5
6
7
8
9
10
11
12
13
class C{//C类通过接口Interface1依赖(使用)D类,但只会用到operation1,4,5方法
void depend1(Interface1 i){
i.operation1();
}

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

void depend5(Interface1 i){
i.operation5();
}
}

问题分析和使用接口隔离原则改进

  1. 如上述代码所示,A类通过接口Interface1依赖B类,C类通过接口Interface1依赖D类,

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

  2. 将接口Interface1拆分为独立的几个接口,A类和C类分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。

  3. 接口Interface1中出现的方法,根据实际情况拆分为三个接口

  4. 代码实现:

    Interface1拆成三个接口:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    interface Interface1{
    void operation1();
    }

    interface Interface2{
    void operation2();
    void operation3();
    }

    interface Interface3{
    void operation4();
    void operation5();
    }

    B类实现Interface1,2:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class B implements Interface1,Interface2{

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

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

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

    }

    D类实现1,3接口:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    class D implements Interface1,Interface3{

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

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

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

    A类:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class A{//A类通过接口Interface1,Interface2依赖(使用)B类,但只会用到operation1,2,3方法
    void depend1(Interface1 i){
    i.operation1();
    }

    void depend2(Interface2 i){
    i.operation2();
    }

    void depend3(Interface2 i){
    i.operation3();
    }
    }

    C类:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class C{//C类通过接口Interface1,Interface3依赖(使用)D类,但只会用到operation1,4,5方法
    void depend1(Interface1 i){
    i.operation1();
    }

    void depend4(Interface3 i){
    i.operation4();
    }

    void depend5(Interface3 i){
    i.operation5();
    }
    }

    使用:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public static void main(String[] args) throws ParseException {
    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. 高层模块不应该依赖低层模块,二者都应该依赖其抽象。

  2. 抽象不应该依赖细节,细节应该依赖抽象

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

  4. 依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定得多;

    以抽象为基础搭建的架构比以细节为基础的架构要稳定得多。

    在Java中,抽象指的是接口或抽象类。细节就是具体的实现类。

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

应用示例

1.请编程完成Person 接收消息的功能。

2.原始代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Email{
public String getInfo(){
return "电子邮件信息:hello";
}
}

/**
分析:
1. 该方式简单,容易想到
2. 如果我们获取的对象是微信,短信等等,则需要新增类,同时Person也要新增相应的接收方法
3.解决思路:引入一个抽象的接口IReceiver,表示接收者,这样Person类与接口IRecevier发生依赖,因为Email,微信等属于接收的范围,他们各自实现,IReceiver接口就ok,这样就符合依赖倒转原则。
**/
class Person{
void receive(Email email){
System.out.println(email.getInfo());
}
}

public static void main(String[] args) throws ParseException {
Person person = new Person();
person.receive(new Email());
}

3.改进后代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface IReceiver{
String getInfo();
}

class Email implements IReceiver{
public String getInfo(){
return "电子邮件信息:hello";
}
}

class QQ implements IReceiver{
public String getInfo(){
return "QQ信息:你好";
}
}

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

依赖关系传递的三种方式和应用案例

1.接口传递实现依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//开关的接口
interface IOnAndOff{
void on(ITV itv);
}


interface ITV{//具体的tv(如电视,ipad等)打开方式自己实现
void play();
}

//实现接口
class OnAndOff implements IOnAndOff{

@Override
public void on(ITV itv) {
itv.play();
}
}

2.构造方法传递实现依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//开关的接口
interface IOnAndOff{
void on();
}


interface ITV{//具体的tv(如电视,ipad等)打开方式自己实现
void play();
}

//实现接口
class OnAndOff implements IOnAndOff{
private ITV itv;

public OnAndOff(ITV itv) {
this.itv = itv;
}

@Override
public void on() {
itv.play();
}
}

3.setter方式传递实现依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//开关的接口
interface IOnAndOff{
void on();
void setTv(ITV itv);
}

interface ITV{//具体的tv(如电视,ipad等)打开方式自己实现
void play();
}

//实现接口
class OnAndOff implements IOnAndOff{
private ITV itv;

@Override
public void setTv(ITV itv) {
this.itv = itv;
}

@Override
public void on() {
itv.play();
}
}

依赖倒转原则的注意事项和细节

  1. 低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好。
  2. 变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化。
  3. 继承时遵循里氏替换原则。

4.里氏替换原则

关于继承性的思考和说明

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

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

基本介绍

  1. 里氏替换原则通俗的来讲就是:子类可以扩展父类的功能,但不能改变父类原有的功能。
  2. 在使用继承时,遵循里氏替换原则,在子类中尽量不要重写父类方法。
  3. 里氏替换原则告诉我们,继承实际上让两个类耦合性增强了,在适当的情况下,可以通过聚合,组合,依赖来解决问题。
  4. 在程序中尽量使用基类类型来对对象进行定义,而在运行时再确定其子类类型,用子类对象来替换父类对象。

示例

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 Base{
//把更加基础的方法和成员写到Base类
}

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

//增加了一个新功能:完成
class B extends Base{
//如果B需要使用A的方法,使用组合关系,而不是继承A
private A a = new A();

//返回两个数的和
public int func1(int a,int b){
return a+b;
}

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

public int func3(int a,int b){
return this.a.func1(a,b) +9;
}
}

5.开闭原则

基本介绍

  1. 开闭原则是编程中最基础,最重要的设计原则。
  2. 一个软件实体如类,模块和函数应该对扩展性(提供方)开放,对(使用方)修改关闭。用抽象构建框架,用实现扩展细节。
  3. 当软件需求发生变化时,尽量通过扩展软件实体的行为来实现变化,而不是通过修改已有的代码来实现变化。
  4. 编程中遵循其他原则,以及使用设计模式的目的就是遵循开闭原则。

示例

初始代码:

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
class Shape{
int m_type;
}

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

class Circle extends Shape{
public Circle() {
super.m_type = 2;
}
}

//用于绘图的类
class GraphicEditor{//使用方
//接收Shape对象,然后根据type,来绘制不同的图形
public void drawShape(Shape shape){
if (shape.m_type == 1)
drawRectangle(shape);
else if (shape.m_type == 2)
drawCircle(shape);
}

private void drawCircle(Shape shape) {
System.out.println("绘制圆形");
}

private void drawRectangle(Shape shape) {
System.out.println("绘制矩形");
}
}


public static void main(String[] args) throws ParseException {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());//绘制矩形
graphicEditor.drawShape(new Circle());//绘制圆形
}

上述代码优缺点:

  1. 优点好理解,简单易操作
  2. 缺点:违反了设计模式的ocp原则,即对扩展开放(提供方),对修改关闭(使用方)。
  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
31
32
33
34
35
36
37
38
39
40
41
abstract class Shape{
int m_type;
public abstract void draw();//抽象方法
}

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

@Override
public void draw() {
System.out.println("绘制矩形");
}
}

class Circle extends Shape{
public Circle() {
super.m_type = 2;
}

@Override
public void draw() {
System.out.println("绘制圆形");
}
}

//用于绘图的类
class GraphicEditor{
//接收Shape对象,然后根据type,来绘制不同的图形
public void drawShape(Shape shape){
shape.draw();
}
}


public static void main(String[] args) throws ParseException {
GraphicEditor graphicEditor = new GraphicEditor();
graphicEditor.drawShape(new Rectangle());//绘制矩形
graphicEditor.drawShape(new Circle());//绘制圆形
}

6.迪米特法则

基本介绍

  1. 一个对象应该对其他对象保持最少的了解。
  2. 类与类的关系越密切,耦合度越大。
  3. 迪米特法则(Demeter Principle)又叫最少知道原则。即一个类对自己依赖的类知道的越少越好。也就是说,对于被依赖的类不管多么复杂,都尽量将逻辑封装在类的内部。对外除了提供的public方法,不对外泄露任何信息。
  4. 迪米特法则还有个简单的定义:只与直接的朋友通信
  5. 直接的朋友:每个对象都会与其他对象有耦合关系,只要两个对象之间有耦合关系,我们就说这两个对象之间是朋友关系。耦合的方式很多,依赖,关联,组合,聚合等。其中,我们称出现成员变量,方法参数,方法返回值中的类为直接的朋友,而出现在局部变量中的类不是直接朋友。也就是说,陌生的类最好不要以局部变量的形式出现在类的内部。

应用示例

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

初始代码:

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
//学校总部员工类
class Employee{
private String id;

public String getId() {
return id;
}

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

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

public String getId() {
return id;
}

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

//管理学院员工的管理类
class CollegeManager{
public List<CollegeEmployee> getAllEmployee(){
ArrayList<CollegeEmployee> collegeEmployees = new ArrayList<>();
for (int i = 0; i < 10; i++) {
CollegeEmployee collegeEmployee = new CollegeEmployee();
collegeEmployee.setId("学院员工ID:"+i);
collegeEmployees.add(collegeEmployee);
}
return collegeEmployees;
}
}

//学校总部员工的管理类
//该类的直接朋友:Employee,CollegeManager
//CollegeEmployee是陌生的类,出现在了局部变量,这违反了迪米特法则
class SchoolManager{
public List<Employee> getAllEmployee(){
ArrayList<Employee> employees = new ArrayList<>();
for (int i = 0; i < 5; i++) {//这里是模拟数据
Employee employee = new Employee();
employee.setId("学校总部员工ID:"+i);
employees.add(employee);
}
return employees;
}

void printAllEmployee(CollegeManager collegeManager){
//CollegeEmployee是陌生类,出现在了局部变量中
//解决思路:将输出学院员工id的代码封装到CollegeManager中
List<CollegeEmployee> collegeEmployeeList = collegeManager.getAllEmployee();
System.out.println("------学院员工-------");
for (CollegeEmployee collegeEmployee : collegeEmployeeList) {
System.out.println(collegeEmployee.getId());
}

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

public static void main(String[] args) throws ParseException {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}

按照迪米特法则,应该避免类中出现这样非直接朋友关系的耦合。

改进代码:

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
//学校总部员工类
class Employee{
private String id;

public String getId() {
return id;
}

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

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

public String getId() {
return id;
}

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

//管理学院员工的管理类
class CollegeManager{
public List<CollegeEmployee> getAllEmployee(){
ArrayList<CollegeEmployee> collegeEmployees = new ArrayList<>();
for (int i = 0; i < 10; i++) {
CollegeEmployee collegeEmployee = new CollegeEmployee();
collegeEmployee.setId("学院员工ID:"+i);
collegeEmployees.add(collegeEmployee);
}
return collegeEmployees;
}

public void printCollegeEmployee(){
List<CollegeEmployee> collegeEmployeeList = this.getAllEmployee();
System.out.println("------学院员工-------");
for (CollegeEmployee collegeEmployee : collegeEmployeeList) {
System.out.println(collegeEmployee.getId());
}
}
}

//学校总部员工的管理类
//该类的直接朋友:Employee,CollegeManager
class SchoolManager{
public List<Employee> getAllEmployee(){
ArrayList<Employee> employees = new ArrayList<>();
for (int i = 0; i < 5; i++) {//这里是模拟数据
Employee employee = new Employee();
employee.setId("学校总部员工ID:"+i);
employees.add(employee);
}
return employees;
}

void printAllEmployee(CollegeManager collegeManager){
collegeManager.printCollegeEmployee();
List<Employee> employeeList = this.getAllEmployee();
System.out.println("------总部员工-------");
for (Employee employee : employeeList) {
System.out.println(employee.getId());
}
}
}

public static void main(String[] args) throws ParseException {
SchoolManager schoolManager = new SchoolManager();
schoolManager.printAllEmployee(new CollegeManager());
}

7.合成复用原则

基本介绍

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

8.设计原则核心思想

  1. 找出应用中可能需要变化之处,把他们独立出来,不要和那些不需要变化的代码混在一起。
  2. 针对接口编程,而不是针对具体实现编程。
  3. 为了交互对象之间的松耦合设计而努力。