Six Design principles
Single responsibility principle
Richter’s substitution principle
Dependency inversion principle
Interface Isolation Principle
Demeter’s rule
Open and closed principle
define
A high-level module should not depend on a low-level module; both should depend on its abstraction; Abstractions should not depend on details, details should depend on abstractions
The idea is to program for the interface, not the implementation.
The characteristics of
-
Dependencies between modules occur through abstraction, while dependencies between implementation classes do not occur directly, but are generated through interfaces or abstract classes.
-
Interfaces or abstract classes do not depend on implementation classes;
-
Implementation classes depend on interfaces or abstract classes.
The sample
Design a customer
Buyers buy goods from TB
Public class Customer {public void shopping(TBShop shop) {// shopping system.out.println (shop.sell()); }}Copy the code
This design has disadvantages if the customer wants to shop from another store (JD)
Modify the purchased merchant
Public class Customer {public void shopping(JDShop) {// shopping system.out.println (shop.sell()); }}Copy the code
If the customer continues to want to change the shop, the code needs to be changed each time, which violates the open and close principle. Instead of relying on abstraction, the customer is bound to the concrete store, violating the dependency inversion principle.
To optimize the
Design a Shop
public interface Shop {
String sell();
}
Copy the code
Design the merchant’s implementation
Public class implements Shop {@override public String sell() {return "implements Shop "; }}Copy the code
Public implements Shop {@override public String sell() {return "implements Shop from TB "; }}Copy the code
The buyer binds to the merchant’s abstraction
Public class Customer {public void shopping(Shop Shop) {// shop.out.println (shop.sell()); }}Copy the code
buy
public class Client { public static void main(String[] args) { Customer customer = new Customer(); customer.shopping(new TBShop()); customer.shopping(new JDShop()); }}Copy the code