Java "veteran" talks about the seven design patterns of source code

A professional programmer always puts code clarity, compatibility, and portability in a very important position. They always enhance the clarity and readability of the code by defining a large number of macros without increasing the length of the compiled code and the running efficiency of the code; they always take into account future code maintenance while coding and upgrade. Even after analyzing 1% of the code, you will deeply understand what kind of code is written by a professional programmer and what kind of code is written by an amateur. And this is something that anyone who hasn't really analyzed standard code can't appreciate.

This article will introduce some classic design pattern ideas:

Common Design Patterns

Proxy mode

Proxy mode: Provides a proxy for other objects to control access to this object.

You can control the method of accessing a certain class (object) in detail, and pre-processing before calling this method (the unified process code is placed in the proxy for processing). Do post-processing after calling this method.

Proxy mode classification:

1. Static proxy (statically defined proxy class, our own statically defined proxy class. For example, we define a star broker class by ourselves)

2. Dynamic proxy (the proxy class is dynamically generated by the program, the proxy class is not defined by us. It is automatically generated by the program) is more important! !

  • JDK's own dynamic proxy
  • javaassist bytecode manipulation library implementation
  • CGLIB
  • ASM (underlying instructions, poor maintainability)

Structure and composition

The proxy mode mainly involves three roles: abstract roles, proxy roles, and real roles (proxied roles).

Abstract Role: Declares the common interface of the real object and the proxy object. That is, the actions that the real object and the proxy object need to achieve together (for example, the landlord and the intermediary must be able to realize the behavior of renting a house, and they can rent the house to you).

Proxy role: The proxy role contains a reference to the real role, so that the real object can be manipulated, and the proxy object provides an interface with the real object, so that it can replace the real object at any time. At the same time, when the proxy object performs the operation of the real object, it can also attach its own operation, which is equivalent to the encapsulation of the real object

Real role: The object represented by the proxy role, that is, the object we will ultimately refer to.

Factory Factory Pattern

The factory pattern is mainly to provide a transition interface for creating objects, so as to shield and isolate the specific process of creating objects and achieve the purpose of improving flexibility.

Factory patterns can be divided into three categories:

  • Simple Factory
  • Factory Method Pattern (Factory Method)
  • Abstract Factory Pattern (Abstract Factory)

These three patterns are progressively abstracted from top to bottom and are more general. GOF divides factory patterns into two categories in the book Design Patterns: Factory Method and Abstract Factory. Think of the Simple Factory pattern as a special case of the Factory Method pattern, and the two are grouped together.

the difference:

Factory method pattern:

  • An abstract product class from which multiple concrete product classes can be derived.

  • An abstract factory class can derive multiple concrete factory classes.

Each concrete factory class can only create one instance of the concrete product class.

Abstract Factory Pattern:

  • Multiple abstract product classes, each abstract product class can derive multiple concrete product classes.

  • An abstract factory class can derive multiple concrete factory classes.

  • Each concrete factory class can create multiple instances of the concrete product class.

the difference:

The factory method pattern has only one abstract product class, while the abstract factory pattern has multiple.

The concrete factory class of the factory method pattern can only create one instance of the concrete product class, while the abstract factory pattern can create multiple instances.

Singleton singleton pattern

  • There can only be one instance of the singleton pattern.
  • A singleton class must create its own unique instance.
  • A singleton class must provide this instance to other objects.

Guarantees that there is only one instance of a class, and provides a global access point to it.

A "veteran" who has been soaking in Java for ten years talks about the seven design patterns of source code

Singleton pattern structure diagram

Singleton mode (Singleton) is the most opposite of several creation modes. Its main feature is not to generate a new instance according to user program calls, but to control the uniqueness of instances of a certain type. From the above figure, we know that it contains There is only one role, the Singleton, which has a private constructor, which ensures that the user cannot directly instantiate it via new. In addition, this pattern includes a static private member variable instance and a static public method Instance(). The Instance() method is responsible for checking and instantiating itself, and then storing it in a static member variable to ensure that only one instance is created.

There is a prerequisite for using the Singleton pattern: a singleton pattern should be used when a system requires only one instance of a class. Conversely, if a class can have several instances coexisting, don't use the singleton pattern.

Do not use the singleton pattern to access global variables. This violates the purpose of the singleton pattern, and it is better to put it in the static member of the corresponding class.

Do not make the database connection a singleton, because a system may have multiple connections to the database, and in the case of a connection pool, the connection should be released as soon as possible. Singleton mode uses static members to store class instances, so resources may not be released in time, causing problems.

Delegate delegation pattern

The delegation pattern (Delegate) is a pattern commonly used in object-oriented design patterns. The principle of this mode is that class B and class A are two classes that have nothing to do with each other. B has exactly the same methods and attributes as A; and when calling a method in B, the attribute is calling the method and attribute with the same name in A. B seems to be an intermediary authorized by A. The third-party code does not need to know the existence of A, nor does it need to have a direct connection with A. It can directly use the functions of A through B, so that it can not only use the various public functions of A, but also effectively integrate A. protected.

Advantages of delegation mode:

  • A single class cannot express complex designs
  • Design split
  • easy to reuse
  • relatively independent
  • Clear function definition, separation of behavior interface
  • Loosely coupled, easy to extend

strategy strategy pattern

Define a series of algorithms, encapsulate each algorithm, and make them interchangeable. This pattern allows the algorithm to vary independently of the client using it. Also known as policy mode (Policy). (Definea family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithmvary independently from clients that use it. )

The strategy pattern distinguishes the object itself from the operation rules, and its function is very powerful, because the core idea of ​​this design pattern itself is the idea of ​​polymorphism of object-oriented programming.

A "veteran" who has been soaking in Java for ten years talks about the seven design patterns of source code

Strategy Pattern Structure

Use Strategy mode when

  • Many related classes simply behave differently. "Strategies" provide a way to configure a class with one of several behaviors. That is, a system needs to dynamically choose one of several algorithms.
  • A different variant of an algorithm needs to be used. For example, you might define some algorithms that reflect different space/time tradeoffs. When these variants are implemented as a class hierarchy of an algorithm, the strategy pattern can be used.
  • Algorithms use data that clients shouldn't know. The strategy pattern can be used to avoid exposing complex, algorithm-related data structures.
  • A class defines various behaviors, and these behaviors appear in the form of multiple conditional statements in the operation of this class. Move the relevant conditional branches into their respective Strategy classes in place of these conditional statements.

Prototype prototype pattern

The main idea of ​​​​the prototype pattern is to clone a new object based on an existing object. Generally, there is a clone method provided inside the object, and a copy of an object is returned by this method. This way of creating an object is compared to what we said before. There are still differences between several types of creational modes. The factory mode and abstract factory described earlier are the process of encapsulating a specific new operation through a factory and returning a new object. Sometimes we create an object through such a creation factory. It is worthwhile, especially in the following scenarios, it may be simpler and more efficient to use the prototype mode.

  • Use the Prototype pattern when a system should be created, composed and represented independently of its product
  • when the class to be instantiated is specified at runtime, e.g. by dynamic loading;
  • To avoid creating a factory class hierarchy parallel to the product class hierarchy
  • When an instance of a class can only have one of several different state combinations. It may be more convenient to build a corresponding number of prototypes and clone them than to manually instantiate the class with the appropriate state each time. (That is, when we are dealing with some objects that are relatively simple, and the differences between the objects are small, maybe only a few fixed properties are different, it may be more appropriate for us to use the prototype pattern).

A "veteran" who has been soaking in Java for ten years talks about the seven design patterns of source code

Prototype Pattern Structure

Template template mode

  • The template method pattern is a behavioral pattern of a class. In its structure diagram, there is only the inheritance relationship between classes, and there is no object association relationship.
  • The board method pattern is a basic code reuse technology based on inheritance, and the structure and usage of the template method pattern is also one of the cores of object-oriented design. In the template method pattern, you can put the same code in the parent class and put different method implementations in different subclasses.
  • In the template method pattern, we need to prepare an abstract class, implement part of the logic in the form of concrete methods and concrete constructors, and then declare some abstract methods to allow subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways and thus have different implementations of the remaining logic, which is what the template method pattern is for. The template method pattern embodies many important ideas of object-oriented, and is a pattern with high frequency.

Template methods should be used in the following cases:

  • Implement the invariant parts of an algorithm once and leave the mutable behavior to subclasses.
  • Behavior common to subclasses should be extracted and concentrated into a common parent class to avoid code duplication. First identify the differences in existing code and separate the differences into new operations. Finally, replace the different code with a template method that calls these new operations. The source code analysis in the full text can be learned for free in the group 619881427. Those who are interested can join in.
  • Control subclass extensions. Template methods only call "hook" operations at specific points, thus allowing extension only at those points.

A "veteran" who has been soaking in Java for ten years talks about the seven design patterns of source code

Template pattern structure

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324377657&siteId=291194637