Six Design principles
Single responsibility principle
Richter’s substitution principle
Dependency inversion principle
Interface Isolation Principle
Demeter’s rule
Open and closed principle
define
There should be one and only one reason for a class to change.
In plain English, do your own work.
The characteristics of
- A singleton class has only one instance object;
- The singleton object must be created by the singleton class itself;
- A singleton class externally provides a global access point to that singleton.
The sample
Before modification
Public interface RealEstate {** ** generate RealEstate */ void generateEstate(); /** * generateBuilding(); /** * generateUnit(); /** * generateRoom */ void generateRoom(); }Copy the code
Take real estate as an example, the process of creating real estate: create a building -> create a building -> create a unit -> create a room
The single responsibility principle requires that an interface or a class can only have one reason to change. That is, an interface or a class can only have one responsibility, which is responsible for one thing. The interfaces above are responsible for four things respectively, violating the single responsibility principle.
If you find a class with multiple responsibilities, ask the question: Can you split the class into multiple classes? If necessary, separate and don’t overload one class.
After transforming
building
Public interface Estate {** ** generateEstate */ void generateEstate(); /** * delete property */ void deleteEstate(); Void editEstate(); }Copy the code
Storied building
Public interface Building {** ** generateBuilding */ void generateBuilding(); /** * void deleteBuilding(); /** */ void editBuilding(); }Copy the code
unit
Public interface Unit {/** * generateUnit */ void generateUnit(); /** * deleteUnit */ void deleteUnit(); /** * editUnit */ void editUnit(); }Copy the code
The room
Public interface Room {/** * generateRoom */ void generateRoom(); /** * deleteRoom */ void deleteRoom(); /** * editRoom */ void editRoom(); }Copy the code
advantages
1) Reduce the complexity of classes so that each class has only one responsibility.
2) The readability and maintainability of the class are improved
3) Reduce the risk caused by change.