软件设计原则及设计模式

一. 软件六大设计原则(SOLID)

  • Single Responsibility Principle:单一职责原则
  • Open Closed Principle:开闭原则
  • Liskov Substitution Principle:里氏替换原则
  • Law of Demeter:迪米特法则
  • Interface Segregation Principle:接口隔离原则
  • Dependence Inversion Principle:依赖倒置原则

把这六个原则的首字母联合起来(两个 L 算做一个)就是 SOLID (solid,稳定的),其代表的含义就是这六个原则结合使用的好处:建立稳定、灵活、健壮的设计。下面我们来分别看一下这六大设计原则。

1.1 单一职责原则(Single Responsibility Principle

一个类应该只有一个发生变化的原因

There should never be more than one reason for a class to change.

1.2 开闭原则(Open Closed Principle)

一个软件实体,如类、模块和函数应该对扩展开放,对修改关闭

Software entities like classes, modules and functions should be open for extension but closed for modification

1.3 里氏替换原则(Liskov Substitution Principle)

所有引用基类的地方必须能透明地使用其子类的对象

Functions that use use pointers or references to base classes must be able to use objects of derived classes without knowing it.

1.4 迪米特法则(Law of Demeter)

只与你的直接朋友交谈,不跟“陌生人”说话

Talk only to your immediate friends and not to strangers

其含义是:如果两个软件实体无须直接通信,那么就不应当发生直接的相互调用,可以通过第三方转发该调用。其目的是降低类之间的耦合度,提高模块的相对独立性。

1.5 接口隔离原则(Interface Segregation Principle)

  • 客户端不应该依赖它不需要的接口。
  • 类间的依赖关系应该建立在最小的接口上。

Clients should not be forced to depend upon interfaces that they don`t use.
The dependency of one class to another one should depend on the smallest possible.

注:该原则中的接口,是一个泛泛而言的接口,不仅仅指具体的接口,还包括其中的抽象类。

1.6 依赖倒置原则(Dependence Inversion Principle)

  • 上层模块不应该依赖底层模块,它们都应该依赖于抽象。
  • 抽象不应该依赖于细节,细节应该依赖于抽象。

High level modules should not depend upon low level modules. Both should depend upon abstractions.
Abstractions should not depend upon details. Details should depend upon abstractions.

二. 软件设计23种模式

2.1 GOF(四人帮,全拼 Gang of Four)

在 1994 年,由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 四人合著出版了一本名为 Design Patterns - Elements of Reusable Object-Oriented Software(中文译名:设计模式 - 可复用的面向对象软件元素) 的书,该书首次提到了软件开发中设计模式的概念。

四位作者合称 GOF(四人帮,全拼 Gang of Four)。他们所提出的设计模式主要是基于以下的面向对象设计原则。

  • 对接口编程而不是对实现编程。
  • 优先使用对象组合而不是继承。

2.3 设计模式的类型

在Design Patterns - Elements of Reusable Object-Oriented Software(中文译名:设计模式 - 可复用的面向对象软件元素) 中所提到的,总共有 23 种设计模式。这些模式可以分为三大类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)、行为型模式(Behavioral Patterns)。

创建型模式

这些设计模式提供了一种在创建对象的同时隐藏创建逻辑的方式,而不是使用 new 运算符直接实例化对象。这使得程序在判断针对某个给定实例需要创建哪些对象时更加灵活。

结构型模式

这些设计模式关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。

行为型模式

这些设计模式特别关注对象之间的通信。

参考:
https://www.runoob.com/design-pattern/design-pattern-intro.html
https://www.jianshu.com/p/3268264ae581

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章