Singleton
目的: To create one and only one instance of an objects.
Private constructor, static getInstance method like global variable but saves resources (only created when it is needed)
Template:
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
Example for ChocolateBoiler:

Even singleton is implemented in ChocolateBoiler, there still an issue from multithreading

1.Simple solution but will effect performance by using synchronized (factor of 100)

- Eagerly created instance rather than a lazily created one:
private static Singleton uniqueInstance = new Singleton();
Pro: Avoid multithreading issue
Con: will affect performance if this object never get used
https://dzone.com/articles/always-start-with-eager-initialisation
3.Double checked locking pattern:

volatile 是什么?
variable guaranteeing happens-before relationship

Use cases of Singleton:
Logging class
System resource monitoring
Registry
ATM https://dzone.com/articles/singleton-design-pattern-%E2%80%93
Summary
-
Private constructor
-
Public static getInstance method
-
The Singleton Pattern also provides a global access point to that instance.
-
Careful about multithreading issue
-
Choose solution based on resource need

网友评论