What would you follow the principles in the design of a package when the factory
You can use a list of Visitor / Decorator pattern of open source projects / libraries do
When you encode the most common design patterns What? Use under what scenario?
How to achieve a singleton
The so-called single embodiment, and that the entire program has only one instance. This class is responsible for creating your own objects, while ensuring that only one object is created. In Java, commonly used tools need to consume resources in the implementation of the class or create objects.
Feature
- Class constructor private
- Hold their own type of property
- Provide external obtain an instance of static methods
Lazy mode
Thread unsafe lazy initialization, not in the strict sense is not a singleton
public class Singleton {
private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
Starving mode
Thread-safe, more commonly, but prone to waste, because the start initialization
public class Singleton {
private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
Double lock mode
Thread-safe, lazy initialization. In this way double locking mechanism, and in safe multithreading can maintain high performance.
public class Singleton {
private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
Double-check mode, a judge twice, the first time in order to avoid unnecessary instance, the second is to synchronize, avoid multi-threading issues. Because creating singleton = new Singleton () object may be carried out in the JVM reordering, there is a risk in a multithreaded access, use, modification signleton volatile instance variable effectively solve the problem.
Internal static type Singleton
public class Singleton {
private Singleton(){ } public static Singleton getInstance(){ return Inner.instance; } private static class Inner { private static final Singleton instance = new Singleton(); } }
Only the first call getInstance method, the virtual machine to load and initialize Inner instance, only one thread can obtain the lock object initialization, other threads can not be initialized, ensure the uniqueness of the object. At present, this is the way all singleton most recommended mode, but still based on the specific project selection.
Enumeration singleton
public enum Singleton {
INSTANCE; }
Create a default enumerate instances are thread-safe, and are single cases under any circumstances. Actually
- Enum class hides private constructor.
- Enumeration class field of a corresponding instance of the object type