Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Basic concepts and classification of Java design patterns

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the basic concepts and classification of Java design patterns". In daily operation, I believe that many people have doubts about the basic concepts and classification of Java design patterns. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "basic concepts and classification of Java design patterns". Next, please follow the editor to study!

1 the basic concept of the model

Pattern refers to the method or idea of solving a specific domain problem and achieving a set goal. Specifically, the model is a universal and recognized problem-solving method or process summed up by those practitioners in a certain industry according to their actual work experience. The model is not only used in software engineering, but also widely used in daily production activities, such as manufacturing, catering, architectural design, medical and health, education and training, software engineering and so on.

2 what is a design pattern?

First of all, a design pattern is a pattern. In software engineering, design pattern is a general and reusable software design method to solve repetitive problems that occur in a given range. The use of mature and reliable design patterns can improve code reusability, save development time, and achieve more powerful and highly maintainable code. This helps to reduce the total cost of ownership of software products, namely TCO (Total Cost of Ownership). On the other hand, due to the adoption of a unified standard design method (ideas or theoretical knowledge), the productivity and collaboration ability of the development team can be significantly improved.

3 Classification of Java design patterns

In the Java programming language, common design patterns can be divided into three types:

Construction class design pattern: mainly used to define and constrain how to create a new object

Structural class design pattern: mainly used to define how to use multiple objects to combine one or more composite objects

Behavior class design pattern: mainly used to define and describe the interaction rules between objects and define the responsibility boundaries of objects

Figure 3-1 Design pattern classification

3.1 Construction design pattern

The construction class consists of five basic design patterns: singleton pattern, factory pattern, abstract factory pattern, builder pattern, and prototype pattern, as shown in figure 3-2:

Figure 3-2 Construction class design pattern

3.2 structural class design pattern

The structure class consists of eight basic design patterns: adapter pattern, composition pattern, proxy pattern, shared meta pattern, filter pattern, bridge pattern, decoration pattern, and appearance pattern, as shown in figure 3-3:

Figure 3-3 structural class design pattern

3.3 Behavioral design patterns

The behavior class consists of eleven (11) basic design patterns: template method pattern, interpreter pattern, chain of responsibility pattern, observer pattern, strategic mode, command mode, state mode, guest mode, escape mode, iterator mode and memo mode, as shown in figure 3-4:

Figure 3-4 behavior class design pattern

Design patterns are not only limited to the three categories described above, but there are also many design patterns. There are more than 100 known design patterns, such as DAO pattern, dependency injection pattern and MVC pattern.

4Quick understanding of design patterns

In the following content, we will quickly sort out the basic concepts of the 24 design patterns commonly used in Java, in order to have a general understanding of the principle and scope of application of various design patterns.

4.1 Construction class

The build class design pattern provides basic definitions and constraints for creating objects to find an instantiated Java object solution.

4.1.1 Singleton mode-Singleton

The singleton pattern restricts the process of class instantiation to ensure that there is one and only one class instantiated object in the Java virtual machine (JVM). Singleton pattern is one of the most commonly used and simplest design patterns in Java. The singleton model usually requires the following characteristics:

Singleton mode restricts the instantiation of a class, and only one instantiated object of this class can exist in the Java virtual machine.

The singleton pattern must provide a globally available access entry to get the instantiated objects of this class.

Singleton patterns are often used for logging, driver object design, caching, and thread pooling.

Singleton patterns will also be used in other design patterns, such as abstract factory patterns, builder patterns, prototype patterns, etc.

The internal structure of the singleton's Java class is shown in figure 4-1:

Figure 4-1 singleton pattern class diagram

The following is a sample code listing for the singleton pattern:

4.1.2 Factory Mode-Factory

In the Java programming process, when a superclass (super class) has multiple subclasses (sub class) and needs to create subclass objects frequently, we can adopt the factory pattern. The function of the factory mode is to assign the instantiation of the subclass to the factory class. By judging the input parameters, the factory class automatically instantiates the specific subclass. Three conditions need to be met to implement the factory model:

Super class: a superclass is an abstract class

Subclass (sub class): subclass needs to inherit superclass

Factory class (factory class): factory class instantiates subclasses based on input parameters

Figure 4-2 is a class diagram of the Java factory pattern:

Figure 4-2 Factory pattern UML class diagram

The following is a sample code listing for the factory pattern:

4.1.3 Abstract Factory pattern-Abstract Factory

Abstract factory pattern is very similar to factory pattern, abstract factory pattern can be simply understood as "factory factory". In factory mode, the instantiated object of the product class is returned according to the input parameters provided, and this process needs to determine the specific subclass through logical judgment statements such as if-else or switch. In the abstract factory pattern, each product has a specific factory class corresponding to it, so as to avoid using a large amount of logical judgment code in the coding process. The abstract factory pattern returns a specific factory subclass based on the type of factory entered. The abstract factory class is only responsible for the instance chemical plant subclass and does not participate in the instantiation of the commodity subclass. Figure 4-3 is a UML class diagram of the abstract factory pattern:

Figure 4-3 Abstract Factory pattern

4.1.4 Builder mode-Builder

Builder mode is often used in scenes that require multiple steps to create objects. The main intention of the builder pattern is to transfer the construction logic of the class to the instantiation of the class. when a class has many attributes, when the object of the class is instantiated, it does not necessarily have all the attribute information of the instantiated object. the builder pattern can be used to complete the instantiation process of the class by gradually obtaining the attribute information of the instantiated object. The factory pattern and the abstract factory pattern need to obtain all the attribute information of the instantiated object when instantiating. Figure 4-4 shows the basic logical relationship of the builder pattern:

Figure 4-4 Builder pattern UML class diagram

4.1.5 prototype mode-Prototype

The main role of the prototype pattern is to use existing classes to create a new object by copying (cloning). When it takes a lot of time and system resources to instantiate the objects of a class, the prototype pattern is adopted, the original existing objects are copied (cloned) to create new objects, and then the new objects are modified as needed. The prototype mode requires that the copied object itself has the copy function, which can not be done by the outside world. Figure 4-5 shows the basic logic of the prototype pattern:

Figure 4-5 prototype pattern UML class diagram

4.2 structural class

The structural class design pattern mainly solves the problem of how to combine multiple small objects into a large object, such as using inheritance and interface implementation to combine multiple classes together.

4.2.1 Adapter pattern-Adapter

The main function of the adapter pattern is to enable the existing multiple available interfaces to provide new interface services for the customer service side. In the adapter pattern, the objects responsible for connecting different interfaces become adapters. In real life, we can also find many practical cases to understand the working principle of the adapter, such as the commonly used mobile phone charging head, which acts as an adapter between the mobile phone and the power outlet. It can adapt to different voltages such as 220V, 200V, 120V and so on at the same time, and finally convert the electricity into 5V voltage available for the mobile phone to charge the mobile phone. Figure 4-6 shows the basic principles of the adapter:

Figure 4-6 Adapter pattern UML Class Diagram

4.2.2 combined Mode-Composite

The main function of the combination mode is to make the whole have the same behavior as the part before. For example, if we need to draw a figure (square, triangle, circle or other polygon), we first need to prepare a blank piece of paper, then choose a color to draw the pattern, and then determine the size of the drawing pattern. Whether you are drawing a square or triangle, you need to follow this step. In the process of software design, the meaning of the combination pattern is to ensure that the client is consistent in its operation flow when calling a single object and a composite object. Figure 4-7 shows the basic principles of the combination pattern:

Figure 4-7 combined pattern UML class diagram

4.2.3 Agent mode-Proxy

The main function of the proxy pattern is to control the access behavior to the actual object by providing a proxy object or a placeholder. The proxy pattern is usually used where some complex objects need to be manipulated frequently. By using the proxy pattern, the target object can be manipulated by the proxy class and the operation process can be simplified. Figure 4-8 shows the basic principles of the proxy pattern:

Figure 4-8 proxy pattern UML class diagram

4.2.4 share meta-mode-Flywight

The main role of sharing meta-pattern is to effectively support a large number of fine-grained objects through sharing. For example, when you need to create many objects of a class, you can use the shared meta pattern to reduce the memory load by sharing object information. If you use the shared meta pattern in the software design process, you need to consider the following three issues:

Is there a large number of objects that the application needs to create?

Are there strict requirements for memory consumption and time consumption in the creation of objects?

Can the attributes of an object be divided into internal attributes and external attributes? Does the external property of the object support a client definition?

Figure 4-9 shows the basic principles of the shared meta-pattern:

Figure 4-9 share meta-schema UML class diagram

4.2.5 appearance Mode-Facade

The main function of the appearance pattern is to provide a unified interface for a set of interfaces in the subsystem so that it is easier for the client to use the interfaces in the subsystem. The simple understanding is that the appearance pattern defines a higher-level interface for many complex interfaces. The purpose of the appearance pattern is to make the interface easier to use, and figure 4-10 shows the basic principles of the appearance pattern:

Figure 4-10 appearance pattern UML class diagram

4.2.6 bridging Mode-Bridge

The main purpose of the bridging pattern is to separate the abstract class from the concrete implementation of the abstract class in order to decouple the structure so that the abstraction and implementation can be changed independently. The implementation of bridging pattern follows composition rather than inheritance first, and when bridging mode is used, it can be implemented internally in the client to a certain extent. Figure 4-11 shows the basic principles of bridging mode:

Figure 4-11 Bridge Mode UML Class Diagram

4.2.7 Decoration Mode-Decorator

The main role of the decorating pattern is to dynamically combine the behavior of classes at run time. Usually, you will add new classes or new methods to extend the existing code base, however, in some cases you need to combine new behavior for an object while the program is running, and you can use decorating mode. Figure 4-12 shows the basic principles of the decoration pattern:

Figure 4-12 Decoration pattern UML Class Diagram

4.2.8 filter mode-Filter

Filter mode uses different criteria to filter a set of objects and combines objects in a decoupled manner through logical operations. Figure 4-13 shows the basic principles of filter mode:

Figure 4-13 filter mode

4.3 behavior class

The behavior class design pattern is mainly used to define and describe the interaction rules and responsibility boundaries between objects, and to provide a solution for better interaction between objects.

4.3.1 template method Mode-Template Method

The main function of template method pattern is to implement an algorithm in a method. Some steps in the algorithm can be abstracted into methods, and the implementation of these methods can be postponed to subclasses. For example, to build a house, we need to design drawings, lay foundations, build walls, install doors and windows and decorate the interior. We can design different house styles (villas, high-rise buildings, board houses, etc.), different doors and windows and different decoration materials and styles, but the order can not be reversed. In this case, we can define a template method that specifies the order in which the method is executed, and defer the implementation of the method to a subclass. Figure 4-14 shows the basic principles of the template method pattern:

Figure 4-14 template method pattern UML class diagram

4.3.2 interpreter mode-Mediator

The main design intention of interpreter (intermediary) pattern is to define an intermediate object and encapsulate the interaction of a group of objects, so as to reduce the coupling of objects, avoid display references between objects, and change the behavior of objects independently. The interpreter (intermediary) mode can provide a centralized interaction medium between different objects in the system and reduce the coupling degree of the components in the system. Figure 4-15 shows the fundamentals of the interpreter (mediation) pattern:

Figure 4-15 interpreter (mediation) pattern UML class diagram

4.3.3 chain of responsibility Mode-Chain of Responsibility

The main function of the chain of responsibility model is to make multiple objects have the opportunity to deal with the same task (request), so as to uncouple the sender and receiver of the request. Try-catch is a typical application case of chain of responsibility model. In a try-catch statement, multiple catch statement blocks can exist at the same time, and each catch statement block is the handler that handles that particular exception. When an exception occurs in a try statement block, the exception will be sent to * catch statement blocks for processing. If * statement blocks cannot handle it, it will be requested to forward to the next catch statement block in the chain. If a block of catch statements still cannot handle the exception, the exception will be thrown up. Figure 4-16 shows the basic principles of the chain of responsibility model:

Figure 4-16 chain of responsibility pattern UML class diagram

4.3.4 Observer mode-Observer

The purpose of the observer pattern is to define an one-to-many dependency between multiple objects. when the state of an object changes, the observer will notify the object that depends on it and react accordingly according to the new state. To put it simply, if you need to be notified in time when the state of an object changes, you can define a listener to listen to the state of the object. The listener is the Observer, and the listener is called the Subject. The Java message Service (JMS) uses the Observer design pattern (as well as the mediation pattern), which allows applications to subscribe to data and publish it to other applications. Figure 4-17 shows the basic principles of the observer mode:

Figure 4-17 Observer mode UML class diagram

4.3.5 Policy Mode-Strategy

The main purpose of the policy pattern is to encapsulate interchangeable methods in separate classes and to have each method implement a common operation. The policy pattern defines the input and output of the policy, and the implementation is done by individual classes. The policy pattern allows a set of policies to coexist and the code does not interfere with each other. it not only separates the logic of selecting the policy from the policy itself, but also helps us to organize and simplify the code. A typical example is the Collections.sort () method, which takes Comparator as the method parameter, and objects are sorted in different ways depending on the Comparator interface implementation class. Figure 4-18 shows the basic principles of the policy pattern:

Figure 4-18 Policy pattern UML Class Diagram

4.3.6 Command mode-Command

The command mode is designed to encapsulate the request inside the object. Direct invocation is a common practice for executing a method, however, sometimes we have no control over the timing and context information when the method is executed. In this case, the method can be encapsulated inside the object, and by storing the information needed by the caller inside the object, the client or service can freely decide when to invoke the method. Figure 4-19 shows the basic principles of command mode:

Figure 4-19 Command mode UML class diagram

4.37 State Mode-State

The state pattern is designed to be more responsive to the state of the object to change its behavior. If we have to change the behavior of an object according to its state, we can define a state variable in the object and use a block of logical judgment statements (such as if-else) to perform different operations according to the state. Figure 4-20 shows the basic principles of the state mode:

Figure 4-20 State Mode UML Class Diagram

4.3.8 Guest Mode-Visitor

The design intention of the guest pattern is to extend the existing class hierarchy without changing it. For example, on a shopping site, when we add different items to the shopping cart and then pay the button, it calculates the total amount to be paid. We can complete the calculation of the amount in the shopping cart class, or we can use the visitor mode to transfer the logic of the purchase payable to the new class. Figure 4-21 shows the basic principles of the guest mode:

Figure 4-21 Guest Mode UML Class Diagram

4.3.9 escape (translation) mode-Interpreter

The escape (translation) pattern is designed to allow you to combine executable objects according to a set of pre-defined combination rules. A basic step to implement the escape (translation) pattern is as follows:

Create a context engine that performs interpretation work

Implement classes according to different expressions and implement interpretation in context

Create a client that takes input from the user and decides which expression to use to output the escaped content

Figure 4-22 shows the basic principles of the escape (translation) pattern:

Figure 4-22 escape (translation) pattern UML class diagram

4.3.10 iterator mode-Iterator

The iterator pattern provides a standard way to iterate over a set of objects. The iterator pattern is widely used in the Java Collection framework, and the Iterator interface provides a way to traverse collection elements. The iterator pattern is not just to traverse the collection, we can also provide different types of iterators according to different requirements. The iterator pattern hides the internal traversal details through the collection, and the client only needs to use the corresponding iterative method to complete the traversal of the element. Figure 4-23 shows the basic principles of iterators:

Figure 4-23 iterator pattern UML class diagram

4.3.11 memo mode-Memento

The memo pattern is designed to provide storage and recovery capabilities for the state of objects. The memo pattern is implemented by two objects-Originator and Caretaker. Originator needs the ability to save and restore the state of an object. It uses inner classes to save the state of an object. The inside is called a memo because it is private to the object, so external classes cannot access it directly. Figure 4-24 shows the basic principles of the memo mode:

Figure 4-24 memo pattern UML class diagram

At this point, the study of "basic concepts and classification of Java design patterns" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report