Design Patterns-Single Responsibility Principle
Introduction
- Design patters are common architecture approaches. (是架构的设计的具体应用方法论)
- Students in Software Engineering Major are usually requirde to take the design patterns in their 3rd year program.
- Popularized by the Gang of Fours book, 1994 – Smalltalk & C++
- Translated to many OOP languages: C#, Jav
Course Structure
Creational (创建型)
Structual (结构型)
Behavioral (行为型)
About Me
- Software Coach in 2012 Software Engineering Lab
The SOLID Design Principles
SOLID is an acronym which stands for the following design principles (and their abbreviations):
• Single Responsibility Principle (SRP)
• Open-Closed Principle (OCP)
• Liskov Substitution Principle (LSP)
• Interface Segregation Principle (ISP)
• Dependency Inversion Principle (DIP)
- Was introduced by Robert C. Martin
- I will reference from these books
Single Responsibility Principle (单一功能原则)
The single-responsibility principle (SRP) is a computer-programming principle that states that every module or class[1] should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class, module or function.
在面向对象编程领域中,单一功能原则(Single responsibility principle)规定每个类都应该有一个单一的功能,并且该功能应该由这个类完全封装起来。所有它的(这个类的)服务都应该严密的和该功能平行(功能平行,意味着没有依赖)。
Example
Supposed we created a notebook which provides a function to add a new note to the notebook and persist all the entries to a file.
1 |
|
However, the save function above raises a problem. Sooner in the future, the the system starts to add more media types such as Journal and BookMark, which has its own Save and Load function.
Later the product manager decides to save the records into the the database instead of a file system.
This migration causes tremendous amount changes of the code because engineers have to go to each sub module, NoteBook, Journal and BookMark to change the Save and Load function. To avoid this problem, we essentially use the seperation of concerns.(忧虑分离)
In this example, to resovle this concern, we separate the pesistence functiionality to a third class, call PersistenceConnector.
1 | struct PersistenceConnector |
This is precisely what is meant by Single Responsibility: each class has only one responsibility, and therefore has only one reason to
change. On the other hand, if you wanted to change the persistence mechanic, this would be changed in PersistenceConnector.
Instead of using the save function from the NoteBook class, we can use the PersistenceConnector to handle hte responsiblity of the persistence. Now, we have the final version of the code with considering the Single Responsibility Principle
1 |
|
An extreme example of an antipattern that violates the SRP is called a God Object. A God Object is a huge class that tries to handle as many concerns as possible, becoming a monolithic monstrosity that is very difficult to work with.