@@ -0,0 +1,2679 @@
+package designpatterns;%0A%0A/**%0A * Singleton:%0A * - creational pattern ensures creating only one instance of object%0A * - the single instance is shared by all classes and threads within application%0A * - improves performance by loading reusable data once without store/reload everytime it needs%0A * - be aware of concurrency, developer should provide thread safety%0A *%0A * Common behaviour:%0A * - uses private final static variable which is accessed by public static method%0A * - has private constructors, so instantiation will occur only inside own class%0A * - setter methods should be protected from multi-thread accesses (i.e. using modifier 'synchronized')%0A *%0A * - Creating singletons:%0A * 1. Instantiation in static class member%0A * 2. Instantiation in static initializer%0A * pros: Once started up, accessing to resource is faster%0A * cons: Slow startup and uses much memory throughout application life-time%0A *%0A * 3. Lazy instantiation (in getter method)%0A * pros: quick startup and use less memory%0A * cons: slow when first time resource is needed%0A *%0A */%0A%0A// 1. Instantiation in static class member%0Aclass Singleton1 %7B%0A    private int value;%0A    final static Singleton1 instance = new Singleton1();%0A    private Singleton1() %7B%7D%0A    public static Singleton1 getInstance() %7B return instance; %7D%0A    public synchronized void addValue(int value) %7B this.value += value; %7D%0A%7D%0A%0A// 2. Instantiation in static initializer%0Aclass Singleton2 %7B%0A    private int value;%0A    final static Singleton2 instance;%0A    static %7B instance = new Singleton2(); %7D%0A    private Singleton2() %7B%7D%0A    public static Singleton2 getInstance() %7B return instance; %7D%0A    public synchronized void addValue(int value) %7B this.value += value; %7D%0A%7D%0A%0A// 3. Lazy instantiation (in getter method)%0Aclass Singleton3 %7B%0A    private int value;%0A    static Singleton3 instance;%0A    private Singleton3() %7B%7D%0A    public synchronized void addValue(int value) %7B this.value += value; %7D%0A%0A    // Not thread-safe%0A    public static Singleton3 getInstance1() %7B%0A        if (instance == null)%0A            instance = new Singleton3();%0A        return instance;%0A    %7D%0A%0A    // Thread-safe, but costly because every calls will be queued%0A    public synchronized static Singleton3 getInstance2() %7B%0A        if (instance == null)%0A            instance = new Singleton3();%0A        return instance;%0A    %7D%0A%0A    // Double-check locking, faster as only first few calls will be queued%0A    public static Singleton3 getInstance3() %7B%0A        if (instance == null)%7B%0A            synchronized (Singleton3.class)%7B%0A                if (instance == null)%0A                    instance = new Singleton3();%0A            %7D%0A        %7D%0A        return instance;%0A    %7D%0A%7D%0Apublic class Singleton %7B%0A%7D%0A

Create Singleton.java