rdoeffinger / Dictionary

"QuickDic" offline Dictionary App for Android. Provided downloadable dictionaries are based on Wiktionaries but can also be created from other sources (see DictionaryPC). Remember to use --recursive when cloning! Fork of project that used to be hosted at code.google.com/p/quickdic-dictionary.
Apache License 2.0
322 stars 69 forks source link

Improve Singletons #134

Closed martingrumbt closed 3 years ago

martingrumbt commented 4 years ago

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:

Expected behaviour

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:

Enum Instantiation

public enum EnumSingleton {
    INSTANCE; 

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

    public EnumSingleton getInstance() {
        return INSTANCE;
    }

    /* other methods */
}

Cons:

Early Instantiation

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

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

    /* other methods */
}

Cons: