🕵️ What is Design Pattern#
Design pattern is a collection of categorized and cataloged code design experiences that are repeatedly used and well-known by most people. The use of design patterns aims to create reusable code, make code easier to understand by others, and ensure code reliability. Undoubtedly, design patterns are beneficial for individuals, others, and systems. Design patterns make code development truly engineering-oriented and serve as the cornerstone of software engineering, just like the bricks of a building. Reasonable application of design patterns in projects can perfectly solve many problems. Each pattern has corresponding principles and core solutions that describe a recurring problem in our surroundings, which is why they can be widely applied. In simple terms:
Pattern: A general solution to a certain type of problem in certain scenarios.
Scenario: The environment in which the project is located.
Problem: Constraints, project goals, etc.
Solution: A general and reusable design that solves constraints and achieves goals.
🗂️ Classification#
- Creational Patterns
Patterns for object instantiation, used to decouple the process of object instantiation. - Structural Patterns
Combining classes or objects to form a larger structure. - Behavioral Patterns
How classes and objects interact, and how responsibilities and algorithms are divided.
🔒 Singleton Pattern#
Ensuring that a class creates only one object
- Private constructor: Since object creation uses constructors, restricting the use of constructors can limit object creation.
- Create a static variable to store the object.
- Provide a static method to retrieve the object.
Eager Singleton#
class HungrySingleton {
private HungrySingleton() {
System.out.println("HungrySingleton constructor executed");
}
static HungrySingleton instance = new HungrySingleton();
static HungrySingleton getInstance() {
return instance;
}
}
Characteristics: When the class is loaded, the static variable instance
will be initialized, and the private constructor of the singleton class will be called, creating the unique instance of the singleton class.
Lazy Singleton#
class LazySingleton {
private LazySingleton() {
System.out.println("LazySingleton constructor executed");
}
private static LazySingleton instance = null;
static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
Characteristics: It is only instantiated when it is first referenced, meaning it is not instantiated when the class is loaded. It is instantiated when the getInstance()
method is first called. This technique is also known as lazy loading, meaning the instance is loaded only when needed.