rdoeffinger/Dictionary

Improve Singletons

Closed this issue · 0 comments

Description

I analysed your project for design patterns.
The implementation of the Singleton pattern in some classes is not done in the common way.
The following classes can be improved:

  • PersistentObjectCache

Expected behaviour

  • Avoid public constructor
  • Avoid forwarding parameters to getInstance-Method for Instantiation
  • Only allow access via getInstance-Method
  • Use volatile/synced variant to be thread safe
  • Avoid Setter to change Instance

Additional context

Here are some blueprints for the Implementation that are all thread safe:

Lazy Instantiation

public class LazySingleton {
    private static volatile LazySingleton instance;

    private LazySingleton() { /* ... */ }

   
    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }

     /* other methods */
}

Pros:

  • arguments can be forwarded on instantiation

Enum Instantiation

public enum EnumSingleton {
    INSTANCE; 
 
    private EnumSingleton() {
        /* ... */ 
    }
 
    public EnumSingleton getInstance() {
        return INSTANCE;
    }
    
    /* other methods */
}

Cons:

  • no forwarding of arguments to the constructor when used first time -> Setters needed

Early Instantiation

public class EarlySingleton {
    public static final EarlySingleton INSTANCE = new EarlySingleton(); 

    private EarlySingleton() { /* ... */ }

    /* other methods */
}

Cons:

  • instantiation when class is loaded
  • no forwarding of arguments to the constructor when used first time -> Setters needed