Hello, everyone, I am Lao Wang. A junior who is learning Java design patterns. Prepare serialized Java design pattern series for review and discussion. Because I am a beginner, the Angle of the station is more what it is, how we should do the Angle of thinking, there is a mistake welcome you to correct, then directly into the topic.

One, the introduction

Why should we know the seven principles? The 23 design patterns we are going to study follow seven principles that constrain each design pattern to increase its extensibility and maintainability. This article will use ‘vulgar’ examples to explain from the following two perspectives, and try to be easy to understand

  • Put forward the official website statement
  • They understand

Second, the classification of

  1. Single responsibility principle
  2. Interface Isolation Principle
  3. Rely on the inversion principle
  4. Richter’s substitution principle
  5. The open closed principle
  6. Demeter’s rule
  7. Synthetic restoration principle

Third, detailed description

1. Principle of single responsibility

  • Official definition:

    Responsibility refers to the cause of class change. If more than one of the motivations of a class is changed, the class has more than one responsibility. The single responsibility principle states that a class or module should have only one reason for change.

  • Own understanding:

    In fact, I do not understand the above statement, but simply describes the idea that a class (object) can only do one thing. Like a bicycle repairman, you can’t ask someone to repair a Mercedes!! If you want to fix a Mercedes, you have to go to a 4s shop. In Java, too, each class should be responsible for its own functionality and be specific.

2. Interface isolation principle

  • Official definition:

    1. The dependency of one class on another class should be based on the smallest interface. 2. Customers should not be forced to rely on methods they do not use. The interface belongs to the customer, not to the class hierarchy in which it resides.

  • Own understanding:

    For example, an interface defines three methods: 1. Find the total population of Guangdong Province () 2. 3. Number of First-tier cities in Guangdong Province

    Now I have a demand, I need to check the total population of Guangdong and check the rank of Guangdong city, so I implemented the interface above, but the third method in the interface: check the number of first-tier cities in Guangdong province is not needed by me, but FOR my own needs, I must also implement it.

    Because this interface has an extra method that I don’t want, it is not dependent on the smallest interface, which violates the dependency of one class on another. Therefore, I should split the three methods of the interface one by one, and then implement the corresponding methods as needed.

3. Dependency inversion principle

  • Official definition:

    Programs rely on abstract interfaces, not concrete implementations. Simply put, requiring that the abstraction be programmed, not the implementation, reduces the coupling between the client and the implementation module.

  • Own understanding:

    For example, there is a class called Laowang that has only one method, goToBeijing, which takes a single argument: Car.

class Laowang{
    public  void  goToBeijing(Car car){
        System.out.println("Lao Wang is open."+car.name+"Go to Beijing"); }}// This is a car object class
class Car{
  	public String name="Car";
} 

/ / the main method
public static void main(String[] args) {
      Laowang laowang = new Laowang();
      Car car = newCar(); laowang.goToBeijing(car); } Lao Wang went to Beijing by carCopy the code

Now came a new trouble, Lao Wang’s Car broke down, then bought a plane (AirPort), but to Beijing method only defined to accept the parameters of a Car object (Car), how to do ???? The solution is simple: change the parameter to the type of aircraft (AirPort).

But is it really good ???? What if the next time my plane breaks down, I buy a Harmony? Wouldn’t we have to change the code again? The correct solution is as follows: let cars and planes inherit from one Vehicle class, and then let Lao Wang go to Beijing to accept the parameter changed to Vehicle.

Now you give me the Audi, I will drive the Audi, you give me the plane, I will drive the plane, you give me the Harmony, I will drive the Harmony to Beijing. Why not? The code is as follows:

class Laowang{
    public  void  goToBeijing(Vehicle vehicle){
        System.out.println("Lao Wang is open."+vehicle.name+"Go to Beijing"); }}// Transportation class
class Vehicle{
   public String name;
}
/ / motor vehicles
class Car extends Vehicle{
    public Car(a){
        super.name="Car"; }}/ / the plane class
class AirPort extends Vehicle{
    public AirPort(a){
        super.name="Plane"; }}/ / the main method
public static void main(String[] args) {
      Laowang laowang = new Laowang();
      Car car = new Car();
      AirPort airPort=new AirPort();
      // Give Lao Wang a car
      laowang.goToBeijing(car);
      // Give Lao Wang the planelaowang.goToBeijing(airPort); } The result is as follows: Lao Wang drives a car to Beijing Lao Wang drives a plane to BeijingCopy the code

This is the dependency inversion principle. Lao Wang to Beijing do not rely on the car class, but should rely on the car interface or abstract class: Vehicle, which is conducive to the expansion of the program. This is the dependency inversion principle. Lao Wang to Beijing do not rely on the car class, but should rely on the car interface or abstract class: Vehicle, which is conducive to the expansion of the program.

4. Richter’s substitution principle

  • Official definition:

    1. If for every object o1 of type S, there is object O2 of type T, such that the behavior of all programs P defined by T does not change when all objects o1 are replaced by O2, then type S is a subtype of type T. 2. All references to a base class must be able to transparently use objects from its subclasses.

  • Own understanding:

    The definition looks complicated, but the idea is simple. Richter’s substitution principle is about inheritance. It says that if A class B inherits from A, you should never override the methods of A parent class. If you have to, let class B not inherit from class A, and then call the parent methods using dependencies, aggregations, compositions, and so on.

5. Open and Close Principle (OCP)

  • Official definition:

    1. The Open closed principle states that “objects in software (classes, modules, functions, etc.) should be open for extension but closed for modification”.

  • Own understanding:

    This official definition seems paradoxical, right? It’s guaranteed to be open for extension, but then closed for modification. Open to expansion, closed to modification. An example: brain circuits jump into dependency inversion !!!! After Lao wang’s car broke down, if you want to fly to Beijing, do you have to modify two places :(1) change Lao wang’s goToBeiJing parameter to plane. (2) Increased the category of aircraft. In fact, this violates the open closed principle. The supplier is the plane, that modify the code has no problem, but for the user (Lao Wang) I need to modify the source code. This violates the open close principle. So let the goToBeiJing parameter accept an abstract class, so that whatever you give me to open, I can open, and I don’t have to change the code.

Demeter’s Rule

  • Official definition:

The Law of Demeter, also known as the least knowledge principle, states that a class should know as little as possible about other classes, and that an object should only communicate with friends and not talk to strangers.

  • Own understanding:

    An object can only communicate with its immediate friends. What is a direct friend? An object that appears in a class’s member variables, member method arguments, or return values can be called a direct friend. Where there are immediate friends, there are strangers. Here’s an example:

    class Laowang{
        	public  void  goToBeijing(Vehicle vehicle){
            System.out.println("Lao Wang is open."+vehicle.name+"Go to Beijing");
            Car car = newCar; }}Copy the code

    In this class, Vehicle appears in the method parameter, so it is a direct friend, but in the method body, a new object Car, so it belongs to a stranger, so we should follow Demeter’s law, reduce the number of friends, do not talk to strangers.

7. Synthesis and restoration principle

  • Official definition:

    The composite/aggregate reuse principle is to use some existing objects in a new object and make them part of the new object. New objects reuse existing functionality by delegating to these objects.

  • Own understanding:

    Synthetic multiplexing means, if you want to use some method on an object, say I want to use method A of class A, how many ways can you do it? (1) Inherit it, and then call. (2) Rely on it, then call. (3) Aggregate it and call. (4) Combine it and call. The principle of composite reuse emphasizes that dependency, aggregation, and composition are preferred in this case. Why is that? Because inheritance is risky, it can destroy the inheritance system. Maintenance difficulties occur.

Fourth, concluding remarks

I have learned JavA2 years, but I still don’t have a good understanding of the idea of facing objects. I only knew there was such a thing before, but now I have learned design pattern, and only after I use it more, I have enough understanding. Such as inheritance, encapsulation, polymorphism, in the design pattern reflected incisively and vividly.