Preface:
There are 23 Design Patterns in Java. The pattern is a solution to the problem. It is applicable to a practical environment. It can also be used in other environments.
Here, we will summarize five common design patterns to facilitate future visits and streamline the content.
1: Singleton Design Mode
This is also the first design pattern for beginners. It solves the problem that only one object exists in the memory of a class.
Step 3: privatize functions 2. Define an object in this class. 3. Provide a method to access the object in this class.
Code:
2. Factory Design Model
The program adds a transition class between the interface and the subclass. Through this transition class, you can dynamically obtain the subclass instantiation object that implements the common interface.
Code:
3. Proxy Design Mode
A proxy subject is used to perform specific business operations on a real subject. The proxy subject is responsible for processing other related businesses. For example, if a customer accesses the network through a proxy, the customer connects to the network (specific business) through the network proxy, and the proxy server completes other Internet-related operations (related business) such as user permissions and access restrictions ).
Code:
4. Observer Design Mode
The so-called observer model. For example, many buyers now closely observe changes in house prices. When house prices change, all buyers can observe that the above buyers belong to the observer model.
Java can use the observable class and observer interface to easily implement the above functions. Of course, the implementation of this mode is not limited to using these two classes.
Code:
5. Adapter Mode
If a class needs to implement an interface with many abstract methods, but it only needs to implement some methods in the interface to achieve the goal, a intermediate transitional class is required at this time, however, this transition class does not need to be used directly. Therefore, it is most appropriate to define this class as an abstract class. Then, the Child classes that inherit this abstract class can overwrite the required methods selectively, this abstract class is the adapter class.
Code: