In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces what are the common design patterns of Java. It is very detailed and has certain reference value. Friends who are interested must finish reading it.
1. Summary of design patterns: 1. What is a design pattern:
Design pattern is a set of repeatedly used code design experience, which aims to reuse the code, make it easier for others to understand, and ensure the reliability of the code. Design patterns are win-win for both people and systems. It makes code writing truly engineering. It is the cornerstone of software engineering, just like the bricks and stones of a building. The reasonable use of design patterns in the project can perfectly solve many problems, and each pattern has its corresponding principles in reality. Each pattern describes a problem that occurs repeatedly around us, and the core solution to the problem, which is why it can be widely used. In general, design patterns fall into three broad categories:
There are five creative patterns: factory method pattern, abstract factory pattern, singleton pattern, builder pattern, prototype pattern.
There are 7 structural patterns: adapter mode, decorator mode, proxy mode, bridge mode, appearance mode, combination mode, sharing meta-mode.
There are 11 behavioral patterns: policy pattern, template method pattern, Observer pattern, responsibility chain pattern, Visitor pattern, Mediator pattern, iterator pattern, Command pattern, State pattern, memo pattern, interpreter pattern.
In fact, there are two types: concurrency mode and thread pool mode, which can be described as a whole with a picture:
2. Six principles of design pattern:
(1) opening and closing principle (Open Close Principle):
The opening and closing principle means that it is open to expansion and closed to modification. When extending the program, we can't modify the original code. To achieve this effect, we need to use interfaces or abstract classes.
(2) the principle of dependency inversion (Dependence Inversion Principle):
The principle of dependency inversion is the basis of the principle of opening and closing, which refers to programming for interfaces, relying on abstraction rather than concrete.
(3) the Richter substitution principle (Liskov Substitution Principle):
The Richter substitution principle is the cornerstone of inheritance and reuse. Only when the subclass can replace the base class, and the function of the system is not affected, the base class can be reused, and the subclass can add new behavior to the base class. So the Richter substitution principle refers to any place where a base class can appear, a subclass must appear.
The Richter substitution principle is a supplement to the "open-closed principle". The key step to realize the "open-closed principle" is abstraction, and the inheritance relationship between the base class and the subclass is the concrete realization of abstraction. therefore, the Richter substitution principle is the specification of the concrete steps to realize abstraction.
(4) Interface isolation principle (Interface Segregation Principle):
Using multiple isolated interfaces is better than using a single interface, which reduces the coupling and dependence between interfaces, and is convenient for upgrade and maintenance.
(v) the Dimitt principle (Demeter Principle):
The Demeter principle, also known as the least known principle, means that a class should minimize interaction with other entities, make the system functional modules relatively independent and reduce the coupling relationship. The original intention of this principle is to reduce the coupling of classes. Although communication with indirect classes can be avoided, communication is bound to occur through an "intermediary". Excessive use of the Demeter principle will produce a large number of intermediaries and transfer classes, resulting in a large number of system complexity, so it is necessary to weigh repeatedly when using the Demeter rule, not only to achieve a clear structure, but also to achieve high cohesion and low coupling.
(6) the principle of synthetic reuse (Composite Reuse Principle):
Try to use composition / aggregation instead of inheritance.
2. 23 design modes of Java:
Next, we introduce in detail the concepts and application scenarios of 23 design patterns in Java, and analyze them in combination with their characteristics and the principles of design patterns.
1. Create-factory method model:
There are three factory method models:
(1) simple factory model:
Create a factory class and define an interface to create a product class that implements the same interface. First, take a look at the diagram:
(2) Factory method model:
The factory method model is an improvement of the simple factory model, and the defect of the simple factory is that it does not conform to the "opening and closing principle". It is necessary to modify the factory class every time a new product class is added, which is not conducive to the extended maintenance of the system. The factory method abstracts the factory and defines an interface to create the object. Each time you add a new product, you only need to add the product and the corresponding concrete implementation factory class, which decides which product to instantiate, and delays the creation and instantiation of the object to the subclass. in this way, the design of the factory conforms to the "opening and closing principle", and there is no need to modify the original code when expanding. The UML diagram is as follows:
(3) static factory method mode:
The static factory pattern sets the methods in the factory method pattern to static, which can be called directly without the need to create an instance.
Details of the factory method pattern article: the creation of the Java design pattern: detailed explanation of the factory pattern (simple factory + factory method + abstract factory)
2. Create-abstract factory model:
The abstract factory pattern is mainly used to create families of related objects. When a product family needs to be designed to work together, the abstract factory pattern ensures that the client always uses only the objects in the same product family, and by isolating the generation of the concrete class, so that the client does not need to specify the concrete generation class explicitly. All concrete factories implement the common interface defined in the abstract factory, so you only need to change the instance of the concrete factory to change the behavior of the whole software system to some extent.
But the disadvantage of this pattern is that it is troublesome to add new behavior, and if you need to add a new product family object, you need to change the interface and all its subclasses, which will inevitably bring a lot of trouble.
The structure diagram of UML is as follows:
Abstract factory pattern details: the creation of Java design pattern: factory pattern detailed explanation (simple factory + factory method + abstract factory)
3. Creator-builder model:
The builder pattern decomposes the creation steps of complex products into different methods, which makes the creation process clearer and more accurately controls the generation process of complex objects; by isolating the construction and use of complex objects, that is, the creation of the product is separated from the product itself, so that the same construction process can create different objects. And each specific builder is independent of each other, so it is convenient to replace specific builders or add new specific builders, and users can get different product objects by using different specific builders. The structure diagram of UML is as follows:
Details of the builder pattern: the creation of the Java design pattern: the builder pattern
4. Create-singleton model:
The singleton pattern ensures that there is only one instance of a class in the system, which instantiates itself and provides the entire system with a common access point for the instance, which cannot be accessed through any other means except this public access point. The advantages of the singleton model are:
There is only one common instance object in the system, so there is no need to create and destroy objects frequently, which saves system resources and improves system performance.
You can strictly control how and when the customer accesses the singleton object.
There are several ways to write the singleton model, and there are mainly three kinds: the lazy type, the hungry type and the registered type.
Singleton pattern details: the creation of Java design pattern: singleton pattern
5. Create a prototype model:
The prototype pattern is also used for the creation of objects, by copying and cloning an object as a prototype to produce a new object similar to the source object. The UML class diagram is as follows:
In Java, the core of the prototype pattern is that the prototype class Prototype,Prototype class requires the following two conditions:
Implement the Cloneable interface:
Override the clone () method in the Object class to return a copy of the object
The clone () method in the Object class defaults to shallow copy, and if you want to make a deep copy of the object, you need to customize your own replication logic in the clone () method.
Shallow copy: after copying an object, the variables of the basic data type are recreated, and the reference type points to the memory address that the original object points to.
Deep copy: after copying an object, both the basic data type and the reference type are recreated.
Using prototype mode to create objects not only simplifies the steps of object creation, but also performs much better than new, because the clone () method of the Object class is a local method that directly manipulates binary streams in memory, especially when copying large objects, the performance difference is very obvious.
Prototype pattern details: the creation type of Java design pattern: prototype pattern
Above we have introduced five creative patterns, let's start with the following seven structural patterns: adapter mode, decoration mode, proxy mode, appearance mode, bridging mode, combination mode, and sharing meta-mode. The adapter pattern of the object is the origin of various patterns, as shown in the following figure:
6. Structural-adapter pattern:
The adapter pattern is mainly used to convert a class or interface into the format desired by the client, so that the previously incompatible classes can work together and decouple the target class from the adaptor class; at the same time, it also conforms to the "opening and closing principle". You can add new adapter classes without modifying the original code Encapsulating the specific implementation in the adaptor class is transparent to the client class and improves the reusability of the adaptor, but the disadvantage is that the implementation process of replacing the adapter is more complex.
Therefore, the adapter pattern is more suitable for the following scenarios:
(1) the system needs to use existing classes, and the interfaces of these classes do not conform to the interface of the system.
(2) use third-party components, component interface definition is different from their own definition, do not want to modify their own interface, but to use the functions of third-party component interfaces.
Here is a very vivid example of what an adapter pattern is:
There are three main implementations of adapter pattern: the adapter pattern of class, the adapter pattern of object, and the adapter pattern of interface. The usage scenarios of the three are as follows:
Adapter pattern for a class: when you want to convert a class to a class that satisfies another new interface, you can use the class's adapter pattern to create a new class, inherit the original class, and implement the new interface.
Adapter pattern for objects: when you want to convert an object to an object that satisfies another new interface, you can create a Wrapper class that holds an instance of the original class, and in the method of the Wrapper class, just call the method of the instance.
Interface adapter pattern: when you do not want to implement all the methods in an interface, you can create an abstract class Wrapper that implements all the methods. When we write other classes, we can inherit the abstract class.
Adapter pattern details: the structure of Java design pattern: adapter pattern
7. Structural-decorator mode:
The decorator pattern can dynamically add some additional responsibilities to objects to achieve functional expansion, select different decorators at run time to achieve different behaviors, and is more flexible than using inheritance. by arranging and combining different decoration classes, we can create many different behaviors and get more powerful objects. In line with the "opening and closing principle", the decorated class and the decorative class change independently. Users can add new decorative classes and decorated classes according to their needs, and then combine them when using them, and the original code does not need to be changed. The UML structure diagram of the decorator mode is as follows:
However, the decorator mode also has shortcomings, first of all, it will produce a lot of small objects, which increases the complexity of the system, and the second is that troubleshooting is more difficult. For objects decorated many times, finding errors during debugging may need to be checked step by step, which is more cumbersome.
Decorator pattern details: structural type of Java design pattern: decorator pattern
8. Structural-agent mode:
The design motivation of the proxy pattern is to access the real object through the proxy object, by establishing an object proxy class, and the proxy object controls the reference of the original object, so as to realize the operation of the real object. In the proxy mode, the proxy object mainly acts as an intermediary to coordinate and connect the caller (that is, the client) and the callee (that is, the target object), which reduces the coupling degree of the system to a certain extent and protects the target object. However, the disadvantage is that the addition of proxy objects between the caller and the callee may slow down the processing of the request. The structure diagram of UML is as follows:
Agent pattern details: structural type of Java design pattern: agent pattern
9. Structural-bridging mode:
The bridge mode decouples the abstract part of the system from the implementation part, so that they can change independently. In order to make the abstract part and the implementation part change independently, the bridging pattern uses the combination relationship instead of the inheritance relationship, and the abstract part has the interface object of the implementation part. thus, the function of the concrete implementation part can be called through this interface object. In other words, bridging in bridging mode is an one-way relationship, and only the abstract part can use the objects of the implementation part, not the other way around.
The bridge mode accords with the "opening and closing principle" and improves the extensibility of the system. If any one of the two changing dimensions is extended, there is no need to modify the original system; and the implementation details are opaque to customers and can hide the implementation details. However, because the aggregation relationship is based on the abstract layer, developers are required to program for abstractions, which increases the difficulty of system understanding and design. The UML structure diagram of the bridge mode is as follows:
Just like in Java, when we use JDBC to connect to the database, we switch between databases without much code, the reason is that the bridge mode is used, JDBC provides a unified interface, each database provides its own implementation, and then the bridge class creates a driver to connect to the database, which only needs to be switched when using a database. The structure of JDBC is as follows:
In JDBC, the Implementor of the bridge pattern is the Driver interface, the Concrete Implementor role corresponds to MysqlDriver, OracleDriver and MariadbDriver, the extended Refined Abstraction role corresponds to DriverManager, and there is no Abstraction role as the parent class of the extended abstraction role.
Bridge mode details: structural type of Java design pattern: bridge mode
10. Structural-appearance mode:
The appearance pattern is used to access a group of interfaces in the subsystem by providing a unified interface to the client. Using appearance mode has the following benefits:
(1) easier to use: make the subsystem easier to use, so that the client no longer needs to understand the internal implementation of the subsystem, nor does it need to interact with the modules within many subsystems, just with the appearance class.
(2) loose coupling: decoupling the client from the subsystem, making the modules within the subsystem easier to expand and maintain.
(3) better division of access levels: through the rational use of Facade, we can better divide the levels of access, some methods are outside the system, some methods are used inside the system. Centralize the functions that need to be exposed to the outside to the facade, which is not only convenient for the client to use, but also well hides the internal details.
However, if the appearance pattern makes too many restrictions on the subsystem class, it reduces the variability and flexibility, so the appearance pattern is suitable to provide a simple interface for the complex subsystem. improve the ease of use of the system scenarios and the introduction of appearance patterns to decouple the subsystem from the client, and improve the independence and portability of the subsystem.
The UML structure diagram of the appearance pattern is as follows:
Appearance pattern details: structure of Java design pattern: appearance pattern
11. Structural-combination mode:
The combination pattern recursively combines the leaf object and the container object to form a tree structure to represent the "part-whole" hierarchical structure, which makes the user's use of a single object and a combined object consistent. Composite objects can be treated like leaf objects without distinction, so that user programs can be decoupled from the internal structure of complex elements.
The most critical aspect of the composition pattern is that the leaf object and the composition object implement the same abstract construction class, which can represent both the leaf object and the container object. The customer only needs to program against this abstract build class. This is why the combination pattern can handle leaf nodes and object nodes consistently. The UML structure diagram of the combined mode is as follows:
Composition pattern details: structural type of Java design pattern: composition pattern
12. Structural-sharing meta-model:
The sharing meta-pattern effectively supports the reuse of fine-grained objects with small state changes through sharing technology. when there are multiple identical objects in the system, then only one object is shared, and there is no need for each to instantiate one object. greatly reduce the number of objects in the system, thus saving resources.
The core of the shared meta-factory class is the shared meta-factory class, which maintains an object storage pool. when the client needs an object, it first obtains it from the shared meta-pool, and returns directly if there is an object instance in the shared meta-pool. if it does not exist in the shared meta-pool, a new instance of shared meta-object is created and returned to the user, and the new object is saved in the shared meta-pool.
Factory classes usually use collection types to hold objects, such as HashMap, Hashtable, Vector, and so on. In Java, database connection pooling, thread pooling, and so on are applications of sharing meta-patterns.
The UML structure diagram of the shared meta mode is as follows:
In Java, the String type uses the shared meta pattern, and the String object is a final type, which cannot be changed once it is created. While Java's string constants exist in the string constant pool, JVM ensures that there is only one copy of a string constant in the constant pool.
And when it comes to shared pool, we can easily think of JDBC connection pool in Java. Through the management of connection pool, the sharing of database connection is realized. There is no need to recreate the connection every time, which saves the cost of database re-creation and improves the performance of the system.
Details of shared meta-pattern: structural type of Java design pattern: shared meta-pattern
Before we introduced 7 structural design patterns, next we introduce 11 behavioral design patterns: strategy pattern, template method pattern, Observer pattern, iterative subpattern, chain of responsibility pattern, Command pattern, memo pattern, State pattern, Visitor pattern, Mediator pattern, interpreter pattern. Let's take a look at the relationships among the 11 patterns:
13. Behavior-strategy model:
Extract the part of the class that often changes or may change as an abstract policy interface class, and then include an instance of this object in the class, so that the class instance can call the behavior of the class that implements the interface at run time.
For example, defining a series of algorithms, encapsulating each algorithm, and making them interchangeable, so that the algorithm can be changed independently of the customers who use it, this is the policy pattern. The structure diagram of UML is as follows:
The advantage of the policy pattern is that it can change the behavior of the object dynamically, but the disadvantage is that many policy classes are generated, and the decision of the policy pattern rests with the user, and the system only provides the implementation of different algorithms, so the client must know all the policy classes and decide which policy class to use.
Policy mode is suitable for the following scenarios:
(1) the application needs to implement specific functional services, and the program can be used in many ways, so it needs to choose one of several algorithms dynamically.
(2) A class defines multiple behavior algorithms, and these behaviors appear in the form of multiple conditional statements in the operation of the class, so the relevant conditional branches can be moved into their respective Strategy classes to replace these conditional statements.
Strategy pattern details: the behavior type of Java design pattern: strategy pattern
14. Behavioral-template method:
The template method is based on inheritance implementation, declares a template method in the abstract parent class, and defines the execution steps of the algorithm (that is, the algorithm skeleton) in the template method. In the template method pattern, the common part of the subclass can be implemented in the parent class, while the implementation of the characteristic part can be delayed to the subclass, and the characteristic part can be declared as an abstract method in the parent class. so that the subclass can redefine some steps in the algorithm without changing the structure of the algorithm, and different subclasses can implement these logic in different ways.
The advantage of the template method pattern is that it conforms to the "open-close principle", and it can also achieve code reuse, transfer the immutable behavior to the parent class, and remove the duplicate code in the subclass. But the disadvantage is that different implementations need to define a subclass, which leads to the increase of the number of classes, which makes the system larger and the design more abstract. The UML diagram of the template method mode is as follows:
Template method details: behavior type of Java design pattern: template method pattern
15. Behavior-responsibility chain model:
The responsibility chain can organize the processor of the request into a chain and pass the request along the chain, if a processor can handle the request, otherwise the request will be handed over to the superior. The client only needs to send the request to the responsibility chain, without paying attention to the processing details of the request, and decouples the sender and processor of the request through the responsibility chain, which is also the motivation for the design of the responsibility chain.
The responsibility chain pattern can simplify the interconnection between objects, because neither the client nor the processor has clear information about each other, and the processor does not know the structure in the responsibility chain, and the processor only needs to save a reference to the successor. There is no need to save references to all candidates.
In addition, the chain of responsibility mode increases the flexibility of the system, and we can add or change handlers, or even change the order of handlers, but it is possible that a request will not be processed anyway, because it may be placed at the end of the chain.
So the chain of responsibility model has the following advantages:
(1) reduce the degree of coupling and decouple the sender and receiver of the request. Reflected in the code is that there is no need to write a lot of ugly if in the class. Else statement, if we use the responsibility chain, we are facing a black box, we just need to submit the request to one of the processors, and then let the black box be responsible for the delivery.
(2) the object is simplified so that the object does not need the structure of the chain.
(3) increase the flexibility of the system by changing the members of the chain or changing their order, allowing processors to be added or deleted dynamically
(4) it is convenient to add new request processing classes.
But the chain of responsibility model also has some disadvantages:
(1) there is no guarantee that the request will be processed successfully
(2) the performance of the system will be affected to a certain extent, and may cause circular calls.
(3) it may not be easy to observe the characteristics of the runtime, and it is not convenient to debug the code, which hinders debugging.
The UML structure diagram of the chain of responsibility pattern is as follows:
Chain of responsibility pattern details: behavior type of Java design pattern: chain of responsibility pattern
16. Behavioral-observer model:
The observer pattern, also known as the publish-subscribe pattern, defines an one-to-many dependency between objects, and all its dependents (observers) are notified when the state of the target object (the observed) changes. An observation target can correspond to multiple observers, and these observers are not related to each other, so observers can be added and deleted as needed, making the system easier to expand and in line with the open-closed principle. And the observer mode loosely couples the target object and the observer. Although they do not know the details of each other, they can still interact. The target object only knows a specific list of observers, but does not know any specific observer. It only knows that they all have a common interface.
But the disadvantage of the observer model is that if there are many observers, it will take a certain amount of time to inform all the observers, and if there is a circular dependency between the observer and the observed, it may lead to a system crash. and the observer model has no corresponding mechanism to let the observer know how the observed object has changed, but only that the observation target has changed. The UML structure diagram of the observer mode is as follows:
Observer pattern details: behavior type of Java design pattern: observer pattern
17. Behavioral-Visitor Model:
The visitor pattern is a method of separating object data structures from behaviors (operations based on data structures). Through this separation, new operations are dynamically added to an interviewee without other modifications. it makes it easy to add new operations acting on these data structures, and does not need to change each data structure, providing multiple access operations for different types of data structures. This is the design motivation of the visitor pattern.
In addition to making it easier to add access operations, it is also possible to define the operation of the existing class hierarchy without modifying the existing class hierarchy, and centralize the access behavior of the element object into one visitor object. instead of spreading out element classes one by one.
But the disadvantage of the visitor pattern is that it makes it difficult to add new element classes. Each addition of a new element class means adding a new abstract operation to the abstract visitor role and adding a corresponding concrete operation to each concrete visitor class, which violates the requirements of the "opening and closing principle".
So the visitor pattern is suitable for systems that rarely change in the object structure, but often need to define new operations on this object structure, making it easy to increase the number of algorithmic operations; or you need to perform many different and irrelevant operations on an object structure, and you need to avoid polluting these objects, and you don't want to modify the scenarios of these classes as new operations are added.
The UML structure diagram of the visitor pattern is as follows:
From the above UML structure diagram, we can see that the visitor pattern is mainly divided into two hierarchies, one is the visitor hierarchy, which provides abstract and concrete visitors, which is mainly used to declare some operations, and the other is the element hierarchy, which provides abstract and concrete elements, which is mainly used to declare accept operations. The object structure ObjectStructure, as a bridge between the two, stores different types of objects so that different visitors can access them, and the same visitor can access different elements in different ways, so adding new visitors in the visitor pattern does not need to modify the existing code.
The double dispatch technique is used in the visitor mode, which means that when choosing a method, it should be distinguished not only according to the runtime of the message receiver, but also according to the runtime of the parameters. In the visitor mode, the client passes the specific status as a parameter to the specific visitor. Here, the first dispatch is completed, then the specific visitor is used as the method in the "specific status" of the parameter, and at the same time, the this is passed as the parameter. Here, the second dispatch is completed. Double dispatch means that the execution action obtained depends on the type of request and the type of recipient.
Visitor pattern details: behavior type of Java design pattern: visitor pattern
18. Behavioral-intermediary model:
The intermediary pattern encapsulates a series of object interactions through intermediary objects, turning the complex network structure of the relationship between objects into a simple star structure with the intermediary as the core, and the one-to-many association between objects is transformed into one-to-one association. simplify the relationship between objects, easy to understand The relationship between each object is decoupled, and each object no longer interacts with its associated object directly, but communicates with the associated object through the intermediary object, so that the object can be used relatively independently, which improves the reusability of the object and the expansibility of the system.
In the intermediary pattern, the intermediary class is in the core position, which encapsulates the relationship between all the object classes in the system. It can not only simplify the relationship between objects, but also further control the interaction between objects. The UML structure of the mediator pattern is as follows:
However, the intermediary object encapsulates the relationship between objects, which makes the intermediary object become large and complex, bear more responsibilities, and it is difficult to maintain. It needs to know the details of each object and the interaction between them. If it goes wrong, it will lead to problems in the whole system.
Details of intermediary pattern: behavioral type of Java design pattern: intermediary pattern
19. Behavioral-command mode:
The essence of command mode is to encapsulate the request into an object, separate the responsibility of issuing the command from the responsibility of executing the command, the sender and receiver of the command are completely decoupled, and the sender only needs to know how to send the command and does not need to care about how the command is implemented. it doesn't even matter whether the execution is successful or not. The key of the command mode lies in the introduction of the abstract command interface, and the sender is programmed for the abstract command interface. Only the specific commands that implement the abstract command interface can be associated with the receiver.
The advantage of using command mode is that it reduces the coupling of the system, and the new command can be easily added to the system, and it is also easy to design a combined command. But the disadvantage is that some systems have too many specific command classes, because a specific command class needs to be designed for each command.
The UML structure diagram of the command mode is as follows:
Command mode details: behavior type of Java design pattern: command mode
20. Behavior-state model:
State mode, which allows an object to change its behavior when its internal state changes, the object looks as if it has modified its class, that is, it uses the state as an atom to change its behavior, rather than through its behavior.
When the behavior of an object depends on its properties, we call these properties states, and the object is called a state object. For a state object, its behavior depends on its state, such as booking a room, which can only be booked when the room is available, and only if you have booked the room or if the room is available. For such an object, when its external events interact, its internal state will change, resulting in a change in his behavior.
The UML structure diagram of the state mode is as follows:
From the above UML structure diagram, we can see that the advantages of the state mode are:
(1) encapsulate the transition rules, allowing the state transition logic to be integrated with the state object, rather than a huge conditional statement block.
(2) by putting all state-related behaviors into one class, you can easily add new states, and you only need to change the state of the object to change the behavior of the object.
But the disadvantage of the state mode is:
(1) you need to determine the type of state before enumerating states.
(2) it will increase the number of system classes and objects.
(3) the support for the "opening and closing principle" is not friendly, the new state class needs to modify the source code responsible for state transition, otherwise it can not be switched to the new state; and to modify the behavior of a state class also needs to modify the source code of the corresponding class.
So the state mode applies to: the code contains a large number of conditional statements related to the state of the object, and the behavior of the object depends on its state, and its related behavior can be changed according to its state change.
State mode details: behavior type of Java design pattern: state mode
21. Behavioral-memo model:
The memo mode provides a mechanism to restore the state, capture the internal state of the object at a certain time without breaking the encapsulation, and save it outside the object, ensuring that the object can be restored to a certain historical state. The memo mode encapsulates the saved details in a memo, which is inaccessible to objects other than the creator, and implements that even if you want to change the saved details, it does not affect the client. But memo mode is multi-state and multi-backup, which uses more memory and consumes resources earlier. The UML structure of the memo model is as follows:
The core of the memo mode is the memo Memento. What is stored in the memo is some or all of the status information of the originator Originator, which cannot be accessed by other objects, that is, we cannot use objects outside the memo to store these state information. If the internal state information is disclosed, it violates the principle of encapsulation. Therefore, the memo is not accessible to objects other than the original. So in order to encapsulate the memo mode, we need to do some control over the access to the memo:
(1) for the originator: all the information in the memo can be accessed.
(2) caretaker to the person in charge: the data in the memo cannot be accessed, but he can save the memo and pass it to other objects.
(3) other objects: inaccessible and can not be saved, it is only responsible for receiving the memo passed from the person in charge and restoring the status of the originator.
Details of memo mode: behavior type of Java design pattern: memo mode
22. Behavioral-iterator model:
The iterator pattern provides a way to access individual elements in the collection without exposing their internal representations. Leave the responsibility of wandering between elements to the iterator instead of the collection object, thus simplifying the implementation of the collection container and making the collection container focus on what it should focus on, which is more in line with the principle of single responsibility. Avoid filling the abstract interface layer of the collection container with different traversal operations. The UML structure diagram of the iterator pattern is as follows:
Iterator pattern details: behavior of Java design pattern: iterator pattern
23. Behavior-interpreter mode:
Interpreter pattern is to define the grammar of a language and build an interpreter to interpret sentences in the language. By building an interpreter, an example of a specific type of problem that occurs frequently can be solved.
The interpreter pattern describes how to construct a simple language interpreter, which is mainly used in compilers developed in an object-oriented language. It describes how to define a grammar for a simple language, how to represent a sentence in that language, and how to interpret these sentences.
In the interpreter pattern, in addition to using grammar rules to define a language, it can also use abstract syntax trees to more intuitively and better represent the composition of a language, each abstract syntax tree corresponds to a language instance. Abstract syntax tree describes how to construct a complex sentence. Through the analysis of abstract syntax tree, we can identify the Terminator and non-Terminator class in the language. In the interpreter mode, because each kind of Terminator expression, non-Terminator expression will have a specific instance corresponding to it, so the expansibility of the system is better.
The UML of the interpreter mode is as follows:
Interpreter pattern details: behavior of Java design pattern: interpreter pattern
The above is all the content of the article "what are the common design patterns of Java". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.