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

What are the Java design patterns?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the Java design patterns?". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Design pattern creation pattern

Create a model

The purpose of a creative schema is to create an object. When it comes to creating an object, the most familiar thing is to new an object, and then set the relevant properties. However, in many scenarios, we need to provide the client with a more friendly way to create objects, especially when we define the class but need to provide it to other developers.

The singleton mode ensures that there is only one instance of the global singleton class, so you can get it directly when you use it. For example, a connection to the database and bean in Spring can be singleton. There are generally five ways to write the singleton model. The first is the hungry mode, which first instantiates the single case and obtains it directly through the static method. The disadvantage is that the class is instantiated after the class is loaded, which wastes part of the space. The second is the satiety mode, which first sets the single instance to null, and then instantiates it when the single instance is obtained by static method, but there may be multiple threads instantiated at the same time, resulting in concurrency problems. The third is a step-by-step improvement method, which can be synchronized with the synchronized keyword at first, but it is too expensive, and then use volatile to modify the singleton, and then determine whether the singleton has been initialized through a check, and use the synchronized code block if it is not initialized. Check the singleton again to prevent it from being initialized during this period, and then really initialize it. The fourth is to use the static inner class, which is initialized only when it is used, so instantiate the singleton in the inner class and run the instantiated code only when used. Then the external class returns a singleton of the static inner class through static methods. The fifth is the enumeration class, the underlying implementation of the enumeration class is also an inner class. Enumerating classes ensures that each class object is globally unique. So it's the easiest way to make sure it's a singleton. The factory pattern is simple. A factory typically uses a single factory to create instances of multiple classes. The factory pattern generally refers to a factory serving an interface, and the abstract factory pattern for the implementation class of this interface means that a factory serves a product family, and a product family may contain multiple interfaces. The interface also contains multiple implementation classes, which can be bound together through a factory, which is very convenient. The prototype pattern is generally cloned through one instance to obtain more instances of the same prototype. This can be done using the clone method of the instance. There is a concept in the builder pattern called chained invocation, which facilitates the instantiation of a class and generally provides a series of methods for instantiation, which is actually a modification of the set method, changing the originally empty set method to return an this instance, thus realizing the chained call. On this basis, the builder pattern adds the builder method, which is provided to the outside to make calls, and also uses chained calls to complete parameter injection. Structural model

Structural model

The previous creation pattern introduced some of the design patterns for creating objects. The structural patterns introduced in this section are designed to decouple our code by changing the structure of the code, making our code easy to maintain and extend.

Bridging mode

It's a little complicated. It is suggested to refer to the original text

Adapter mode

The adapter pattern is used to adapt two different classes.

Similarities and differences between Adapter pattern and Agent pattern

Comparing these two patterns is actually comparing the object adapter pattern with the proxy pattern, in terms of code structure.

They are very similar and require an instance of a concrete implementation class.

But their purpose is different, the agent mode is to enhance the work of the original method.

The adapter does adaptive work in order to provide "packaging the chicken into a duck and then using it as a duck."

There was no inheritance relationship between chickens and ducks.

Adapter patterns can be divided into class adapters, object adapters, and so on.

The class adapter can adapt itself to the parent class by inheriting the parent class.

The object adapter needs to pass the object into the constructor of another object for wrapping.

Sharing meta-mode

The core of the meta-sharing model lies in the meta-factory class.

/ / the function of the shared meta factory class is to provide a shared meta pool for storing shared meta objects.

/ / when a user needs an object, he / she first obtains it from the shared element pool.

/ / if it does not exist in the share meta pool, a new share meta object is created and returned to the user

/ / Save the new object in the share pool.

/ / share meta-mode

/ / English is Flyweight Pattern. I don't know who translated the word first. I feel that the translation is really difficult to understand. Let's try to force the connection. Flyweight means lightweight, and sharing elements separately means sharing components, that is, reusing generated objects, which is, of course, lightweight.

/ /

/ / the easiest way to reuse objects is to use a HashMap to store each newly generated object. Every time you need an object, go to the HashMap to see if there is one, if not, generate a new object, and then put the object into the HashMap.

/ /

/ / I won't demonstrate this simple code.

Agent mode

/ / have we found that the proxy model is simply "method wrapper" or "method enhancement".

/ / in aspect-oriented programming, forget it and don't flatter the term, in AOP

/ / it is actually the process of dynamic proxy. Like in Spring.

/ / We don't define proxy classes ourselves, but Spring will help us define proxies dynamically.

/ / then dynamically add the code logic we defined in @ Before, @ After, @ Around to the agent.

Appearance mode

Appearance patterns generally encapsulate specific implementation details and provide users with a simpler interface.

You can get what you need through a method call.

Combination mode

/ / the composition pattern is used to represent data with a hierarchical structure, which makes our access to individual objects and composite objects consistent.

/ / Let's look at an example directly. Every employee has attributes such as name, department and salary.

/ / there is also a collection of subordinate employees (although the collection may be empty)

/ / and subordinate employees have the same structure as their own.

/ / there are also attributes such as name and department.

/ / at the same time, there is also a collection of subordinates.

Class Employee {private String name; private String dept; private int salary; private List subordinates; / / subordinate} decorator pattern decorator

The decorator pattern inherits each enhanced class from the highest parent class. Then you can pass the class instance into the enhanced class when you need to enhance the functionality, and then the enhanced class can enhance the functionality of the original class when it is used.

Unlike the proxy pattern, each decoration class in the decorator pattern inherits the parent class and can be encapsulated at multiple levels.

Behavioral model

Behavioral model

The behavioral model focuses on the interaction between the various classes, dividing the responsibilities clearly and making our code clearer.

Strategy mode

The policy pattern generally takes a policy as a class and passes in an instance when you need to specify a policy, so we can pass in the specified algorithm where we need to use it.

Command mode

Command mode is generally divided into three roles: command initiator, command and command receiver.

The command initiator needs to inject a command instance when using it. Then execute the command call.

The command call actually invokes the method of the command recipient to make the actual call.

For example, the remote control button is equivalent to a command, the command runs when the button is clicked, and the method provided by the TV is automatically called.

Template method mode

Template method generally means that a method template is provided, and there are partial implementation classes and partial abstract classes, and the execution order is specified.

Implementation classes are good methods provided by templates. Abstract classes need to be implemented by users themselves.

The template method specifies the execution order of the methods in a template, which is very suitable for some development frameworks, so the template method is also widely used in open source frameworks.

State mode

It's rare.

Observer mode and event monitoring mechanism

The Observer pattern is generally used for data subscriptions between subscribers and message publishers.

Generally divided into observers and topics, observers subscribe to topics and register the instance on the list of observers maintained by the topic.

When the topic updates the data, it automatically pushes the data to the observer or notifies the observer that the data has been updated.

However, because of this way, the coupling relationship of message push is relatively tight. And it's hard to know what the data type is without opening the data.

I know that later, in order to make the data format more flexible, I used the pattern of events and event listeners, event-wrapped event types and event data, decoupled from the subject and the observer.

Topic when an event occurs, all listeners that trigger the event send the event to each listener through the listener list. After listening for the event, first find the corresponding event handler according to the event types you support, and then use the handler to process the corresponding event.

Responsibility chain model

The responsibility chain usually needs to create an one-way linked list, and then the caller only needs to call the header node, which will be automatically transferred. For example, process approval is a good example. As long as the end user submits an application, a responsibility chain is automatically established according to the content information of the application, and then the flow can begin.

This is the end of "what are the Java design patterns"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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