Talking about Design Patterns| Which came first, the chicken or the egg? Is there a design pattern after the code or a design pattern before writing the code?

foreword

First, the three major characteristics of object-oriented

1. Packaging

2. Inheritance

3. Polymorphism

2. Seven object-oriented design principles

1. Single Responsibility Principle

2. Open closed principle

3. Liskov substitution principle

4. Interface Segregation Principle

5. Dependency Inversion Principle

6. The principle of synthetic reuse

7. Law of Demeter

3. Possible interview questions

1. What is the difference between object-oriented and procedural-oriented?

2. What are the characteristics of object-oriented?

3. What is the polymorphic mechanism? How does the Java language implement polymorphism?

4. Tell me about the difference between rewriting and overloading? Can overloaded methods be differentiated by return type?

5. Can the constructor be overridden?

6. What are the five basic principles of object-oriented?

7. What is the difference between an abstract class and an interface?


foreword

        It’s been a long time without text output, and when I opened the editing page, I didn’t know where to start, so I just wrote it as a diary.

        When I was buying a book recently, I bought a copy of "Big Talk Design Patterns" for the 100 minus 50 book category coupons. I have nothing to do or turn two pages before going to bed. I started to blindly type the code for the content of the work. During the code review, the valuable opinions put forward by the big guys were found to be written at the front of the book, but I didn’t realize my problem if I didn’t read it before.

        When I was in college, I learned design patterns just to answer questions in interviews, so I felt that design patterns were illusory things. I knew what design patterns were and didn’t even think about using them when writing code. There is no need to start complaining when entering design mode. What is a design pattern? Is it good code if we use design patterns to write code? Do you want to write code that conforms to a design pattern for the design pattern?

        A design pattern is a set of excellent solutions gradually formed after the code is implemented for a certain scenario, so the appropriate design pattern should be used in the appropriate position, neither to write code for the purpose of applying the design pattern nor to write code without considering the design at all model. This article first makes a foreshadowing overview based on the basic knowledge introduced in the book.

        Recent top quote: "What is done on paper will eventually be shallow, but I never know that this matter has to be done."


First, the three major characteristics of object-oriented

1. Packaging

        Encapsulation is mainly divided into two meanings: one is to encapsulate data and methods (defining classes), and the other is to control access rights (access modifiers).

        The basic unit of encapsulation is the class. Since the purpose of classes is to encapsulate complexity, there are mechanisms within classes to hide implementation complexity. Java provides private and public access modes. The public interface of a class represents everything that external users should know or can know. Private method data can only be accessed through the member code of the class.

2. Inheritance

        Inheritance is the inheritance of subclasses from parent classes, or professionally called derived classes and base classes. In the inheritance relationship, the subclass can inherit the non-private properties and functions of the parent class , and the subclass can extend the properties and methods that the parent class does not have . The third subclass can rewrite the methods of the parent class in its own way .

3. Polymorphism

        " One interface, many methods ". Polymorphism is reflected in the fact that the properties and methods defined in the parent class can have different properties or expressions after being inherited by subclasses. Polymorphism allows an interface to be used by multiple classes , making up for the lack of single inheritance.

        When I was chatting with my roommate that day, I couldn't think of how to describe it, so I gave an example: Animals have a "sound" method, and humans inherit it as "speaking", and dogs inherit it as "dog barking"..... .Aw, then I was beaten by my roommate, she said I seemed to be scolding her? !

2. Seven object-oriented design principles

1. Single Responsibility Principle

        Referred to as the SRP (Single Responsibility Principle) principle, each type (including interfaces and abstractions) has a single functional requirement, and is only responsible for one thing, and cannot cover everything .

        For example, a Modem (modem) interface

interface Modem {
    public void dial(String pno);
    public void hangup();
    public void send(char c);
    public char recv();
}

        There are two responsibilities in this interface: the first is management connection (dial and hangup); the second is data transmission (send and recv), these two responsibilities should be separated.

2. Open closed principle

OCP (Open Closed Principle) principle for short, software entities         (modules, classes, functions, etc.) code to complete the changes.

  • It is open to extension, which means that the behavior of the software entity is extensible. When the requirements change, the modules can be extended to meet the requirements of the requirements changes.
  • The modification is closed, which means that when the software entity is extended, the current software entity does not need to be changed; the code does not need to be modified; the completed class files do not need to be re-edited; Need to recompile again.

        The combination of the two is expressed as: adding a new function should be to expand the code based on the existing code (adding modules, classes, methods, etc.), rather than modifying the existing code (modifying modules, classes, methods, etc.).

3. Liskov substitution principle

        The subclass can replace the parent class and appear anywhere the parent class can appear , and the subclass must fully implement the methods of the parent class. Because of the invasiveness brought by inheritance, it increases coupling and reduces code flexibility. If the parent class modifies the code, the subclass will also be affected. At this time, the Liskov substitution principle is needed. If the subclass cannot fully implement the methods of the parent class, or some methods of the parent class have been "distorted" in the subclass, it is recommended to break the parent-child inheritance relationship and use dependencies, aggregation, composition and other relationships instead of inheritance.

        The advantage is that the robustness of the program is enhanced, and even if subclasses are added, the original subclasses can continue to run.

4. Interface Segregation Principle

        Referred to as the ISP (Interface Segregation Principle) principle, modules should be separated through specific interfaces instead of strong coupling through classes. The client should not rely on interfaces it does not need, and the dependencies between classes should be established on the smallest interface .

        When designing microservice or class library interfaces, if some interfaces are only used by some callers, then we need to isolate this part of the interface and use it for the corresponding callers alone, instead of forcing other callers to also rely on this part An interface that will not be used. Although the interface should be as detailed as possible, there must be a limit. Refining the interface can improve the flexibility of program design, but if it is too small, it will cause too many interfaces and complicate the design. Therefore, we must moderately increase cohesion and reduce external interaction. Make the interface use the fewest methods to accomplish the most things and customize services for classes that depend on the interface. Only the methods it needs are exposed to the calling class, and the methods it does not need are hidden. Only by focusing on providing customized services for a module can we establish minimal dependencies.

5. Dependency Inversion Principle

        Referred to as DIP (Dependency Inversion Principle) principle, the concrete depends on abstraction, the upper layer does not depend on the lower layer, and the core idea is interface-oriented programming. High-level modules do not depend on low-level modules, and they all depend on the same abstraction . This abstract interface is usually defined by high-level modules and implemented by low-level modules. At the same time, abstraction does not depend on specific implementation details, and specific implementation details depend on abstraction. The high-level module is the caller, the low-level module is the concrete implementation class, the abstraction refers to the interface or abstract class, and the details are the implementation class.

        The benefits of Dependency Inversion are difficult to realize in small projects. However, in large and medium-sized projects, the workload caused by changes in requirements can be reduced. Make parallel development more friendly.

6. The principle of synthetic reuse

        Referred to as the CRP (Composite Reuse Principle) principle, also known as the combination/aggregation reuse principle. It requires that when software is reused, as far as possible, use combination or aggregation to achieve it first, and then consider using inheritance relationship to achieve it . If you want to use the inheritance relationship, you must strictly follow the Liskov substitution principle. The composition reuse principle and the Liskov substitution principle complement each other, and both are specific implementation specifications of the opening and closing principle.

        When using combination or aggregate reuse, existing objects can be incorporated into new objects to make them part of new objects, and new objects can call functions of existing objects. It has the following advantages:

  1. It maintains the encapsulation of the class. Because the internal details of the component objects are invisible to the new object, this kind of reuse is also called "black box" reuse;
  2. Low coupling between old and new classes. This kind of reuse requires fewer dependencies, and the only way for new objects to access component objects is through the component object's interface;
  3. The flexibility of reuse is high. This reuse can be done dynamically at runtime, and new objects can dynamically reference objects of the same type as the constituent objects.

7. Law of Demeter

        The law of LoD (Law of Demeter) for short, also known as the principle of least knowledge, that is to say, an object should know as little as possible about other objects. The original intention is to reduce the coupling between classes: Since each class minimizes its dependence on other classes, it is easy to make the functional modules of the system independent and have no (or few) dependencies between them.

        Demeter's law does not want to establish a direct connection between classes. If there is really a need to establish a connection, I hope it can be conveyed through its friend class. Therefore, one of the consequences that may be caused by the application of Dimit's law is that there are a large number of intermediary classes in the system. the complexity.


3. Possible interview questions

1. What is the difference between object-oriented and procedural-oriented?

        Answer: Process-oriented is to analyze the steps needed to solve the problem, and then use functions to realize these steps step by step. When using them, they can be called one by one. Object-oriented is to decompose the constitutive problem into various objects. The purpose of establishing an object is not to complete a step, but to describe the behavior of something in the entire problem-solving step.

        PS: The benefits (advantages) of object-oriented may be mentioned from this :

        1. Easy maintenance
        The structure designed with object-oriented thinking has high readability. Due to the existence of inheritance, even if the requirements are changed, the maintenance is only in partial modules, so maintenance is very convenient and low-cost.

        2. High quality
        At the time of design, existing classes that have been tested in the domain of previous projects can be reused to make the system meet business needs and have high quality.

        3. High efficiency
        In software development, according to the needs of the design, the things in the real world are abstracted to generate classes. Using such a method to solve problems, which is close to daily life and natural way of thinking, is bound to improve the efficiency and quality of software development.

        4. Easy to expand
        Due to the characteristics of inheritance, encapsulation, and polymorphism, a system structure with high cohesion and low coupling is naturally designed, which makes the system more flexible, easier to expand, and lower in cost.

2. What are the characteristics of object-oriented?

        Answer: encapsulation, inheritance, polymorphism

        PS: Based on the above content or my own understanding, I will expand the narrative slightly

3. What is the polymorphic mechanism? How does the Java language implement polymorphism?

        Answer: Polymorphism means that the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable are not determined during programming, but are determined during the running of the program, that is, a reference variable will point to The instance object of which class, and the method implemented in which class the method call issued by the reference variable must be determined during the running of the program.

        Polymorphism is divided into compile-time polymorphism and run-time polymorphism. Among them, polymorphism is static when editing, mainly referring to method overloading. It distinguishes different functions according to the parameter list. After editing, it will become two different functions. There is no polymorphism at runtime. . And runtime polymorphism is dynamic, it is realized through dynamic binding, which is what we call polymorphism.

        There are three necessary conditions for Java to achieve polymorphism : inheritance, rewriting, and upward transformation.

        Inheritance: In polymorphism, there must be subclasses and parent classes that have an inheritance relationship.

        Rewriting: The subclass redefines some methods in the parent class, and when these methods are called, the methods of the subclass are called.

       Upward transformation: In polymorphism, it is necessary to assign the reference of the subclass to the parent class object, only in this way can the reference be able to call the method of the parent class and the method of the subclass.

Only when the above three conditions are met, can we use a unified logic implementation code to process different objects in the same inheritance structure, so as to achieve different behaviors.

4. Tell me about the difference between rewriting and overloading? Can overloaded methods be differentiated by return type?

        Answer: Method rewriting exists between the subclass and the parent class. The method defined in the subclass has the same method name , the same parameter list and the same return type as the method in the parent class ; method overloading refers to the method in the same class Multiple methods have the same name , but these methods have different parameter lists , that is, the number or type of parameters cannot be exactly the same.

        Note: (1) The final method in the parent class cannot be rewritten in the subclass 
             (2) The abstract method in the parent class must be rewritten in the subclass 

        Rewriting, polymorphism between the parent class and the subclass, redefines the function of the parent class. If a method defined in a subclass has the same name and parameters as its parent class, we say that the method is overridden (Overriding), and the subclass can inherit the method in the parent class without rewriting the same method. But sometimes the subclass does not want to inherit the method of the parent class intact, but wants to make certain modifications, which requires method rewriting. Method rewriting is also called method coverage;

        If a method in the subclass has the same method name, return type, and parameter list as a method in the parent class, the new method will overwrite the original method. If you need the original method in the parent class, you can use the super keyword, which refers to the parent class of the current class. And the access modification permission of the subclass function cannot be less than that of the parent class.

        Overloading is a means for a class to handle different types of data in a uniform manner. Multiple functions with the same name exist at the same time, with different numbers/types of parameters. Overloading Overloading is a manifestation of polymorphism in a class.
       When method overloading calls methods, it determines which method to use by passing them different parameter numbers and parameter types, which is polymorphism. When overloading, the method names must be the same, but the parameter types and numbers are different, and the return value types can be the same or different. The return type cannot be used as the criterion for distinguishing overloaded functions.

5. Can the constructor be overridden?

        Answer: First of all, the constructor is used to generate an instance of a class and is used to initialize the instance. The constructor is not a method, so all the modifiers used to modify the characteristics of the method cannot be used to modify the constructor (not equal to the constructor The constructor has these characteristics, although the constructor cannot be modified with static, but it has static characteristics) The constructor can only use the three permission modifiers of public private protected, and cannot have a return statement, so the constructor cannot be rewritten.

        Note: The order in which Java constructs instances is as follows:

        1. Allocate object space and initialize the members in the object to 0 or empty. Java does not allow users to manipulate an object with an indeterminate value

        2. Perform explicit initialization of property values

        3. Execute the constructor

        4. Associate variables with objects in the heap

        The steps to execute the constructor can be divided into the following steps:

        1) Parameters of the Bind constructor

        2) If this is explicitly called, call the this constructor recursively and skip to step 5

        3) Recursively call the explicit or implicit parent class constructor, except Object, because it has no parent class

        4) Perform explicit instance variable initialization

6. What are the five basic principles of object-oriented?

        Answer: SOLID principles (single, open and close, Liskov replacement, interface isolation, dependency inversion), according to the above solution, what are they, and some of them do not specify the five principles, let’s use the above seven principles

7. What is the difference between an abstract class and an interface?

        Answer: The difference between an abstract class and an interface is: the representation content is different, the nature is different, and the member variables are different.

        The content is different: an abstract class indicates that there may already be some specific definitions of methods in the class; an interface can only define the interface of each method (method name, parameter list, return type), and does not care about specific details

        The nature is different: an abstract class is an abstraction of an object, and an interface is a behavior specification;

        Different member variables: member variables in abstract classes can be modified by different modifiers; member variables in interfaces default to static constants (static final).

       

Guess you like

Origin blog.csdn.net/weixin_44187963/article/details/123941160