Six principles of design mode-detailed explanation of the principle of opening and closing and the principle of single responsibility
1. Open Close Principle (OCP)
-
concept
The core of the principle of opening and closing is: open for extension and closed for modification . Its purpose is to improve the scalability of the program and realize hot plugging. That is, every time the requirements change, the original code can be modified without modification . Expand new functions to meet the needs.
-
Simple case
Book selling business:
The following categories are available
1.
Book
This interface contains attributes such as price, book title, author, and basic getter and setter methodspublic interface Book { String getName(); int getPrice(); String getAuthor(); }
2.
NovelBook(小说)
Implemented theBook
classpublic class NovelBook implements IBook{ private String name; //为了防止精度丢失,这里用原有的价格*100的整数来保存 private int price; private String author; public NovelBook(String name, int price, String author) { this.name = name; this.price = price; this.author = author; } @Override public String getName() { return this.name; } @Override public int getPrice() { return this.price; } @Override public String getAuthor() { return this.author; } }
3.
BookStore
Bookstoreprivate static ArrayList<IBook> bookList=new ArrayList<>(); static { bookList.add(new OffNovelBook("红楼梦", 9900, "曹雪芹")); bookList.add(new OffNovelBook("侠客行", 8900, "金庸")); bookList.add(new OffNovelBook("原则", 6900, "瑞达利欧")); bookList.add(new OffNovelBook("海贼王1", 4900, "尾田荣一郎")); } public static void main(String[] args) { System.out.println("卖书的记录如下----------------------"); for (IBook book : bookList) { System.out.println("书籍名称:"+book.getName()+"\t\t作者:"+book.getAuthor()+"\t\t价格:¥"+book.getPrice()/100.0+"元"); } } }
Now, there is such a new demand:
Because of Double Eleven, now we need to discount books of 70 yuan and above 20% off, and 10% off books below 70 yuan. How should we meet this demand now? It is easier to think of: ① modify
NovelBook
thegetPrice
method in this class ②Book
add a new method to the interface. The above two methods are more or less inappropriate. First, if you modify thegetPrice
method, if you want to get the normal price of the book in other places, it will not be satisfied, which changes the original function ; Second, because a new method is added to the interface, this method needs to be added to all implementation classes, which leads to more places that need to be modified ; for the problems encountered above, combined with the principle of opening and closing , We can add an additional discounted novel categoryOffNovelBook
, which inheritsNovelBook
and rewrites itsgetPrice
method so that it can get the discounted price, in this way, it meets the new demand without affecting the original businesscode show as below:
public class OffNovelBook extends NovelBook{ public OffNovelBook(String name, int price, String author) { super(name, price, author); } @Override public int getPrice() { int sellPrice=super.getPrice(); int offPrice=0; if(sellPrice>7000){ offPrice=sellPrice*90/100; }else{ offPrice=sellPrice*80/100; } return offPrice; } }
-
to sum up:
advantage:
1. Facilitate software testing
Because the original code has not been modified, so you only need to test the new code each time
2. Improve code reusability
Because the smaller the granularity, the greater the possibility of being reused
3. Improve software maintainability
Software that complies with the opening and closing principles, because it is only expanding new functions each time and will not have much impact on the original functions, so its stability is strong and easy to maintain
2. Single Responsibility Principle (Single Responsibility Principle, SRP)
-
concept:
As the name implies, it means that a class should have only one reason for its change (that is, only the reason related to other responsibilities) . Its purpose is to reduce complexity, improve readability and maintainability . Imagine if a class has different All kinds of unrelated methods and attributes will definitely dazzle you. Just like, one person has multiple roles, and one person is a team. This seems simple, but it will definitely make that person very tired. As long as everything related to it is related to him. What needs special explanation is that because there is no unique solution to the division of responsibilities, so everyone can decide how to divide according to the situation.
-
Simple case:
Implement a call function:
Phone
Interface, which defines several methods of dialing, calling and hanging uppublic interface Phone { //拨号 void dial(String phoneNumber); //通话 void chat(Object obj); //挂断 void hangup(); }
Simply analyze:
Disadvantages written above:
1. When the client only needs one of the responsibilities, it has to include other unnecessary responsibilities, causing code redundancy
2. The change of a certain responsibility may cause the ability of this class to implement other responsibilities. In layman's terms, it may be too busy for a short time
After careful analysis, it is not difficult to find that the two methods of dialing and hanging up are related to the protocol, and the call is related to the data transmission. Therefore, we can divide the responsibilities according to the analysis:
public interface DataTransfer { void chat(Object obj); }
public interface ConnectionManger { void dial(String phoneNumber); void hangup(); }
-
to sum up
advantage:
1. Reduce complexity
A class is only responsible for one responsibility, the logic is relatively simple
2. Improve readability
Reduced complexity, so readability will improve
3. Improve maintainability
As readability improves, so does maintainability
4. Risk reduction due to changes
According to the single responsibility principle, when a function is modified, the impact on other functions will be significantly reduced