0
Answered

Implementing Strategy pattern along with Singleton

Rishi Sundar Muralidharan 4 years ago updated by anonymous 4 years ago 7

I have different stores (based on how and where data is stored) which are implemented by using the Strategy pattern. There should only be one store at a time and I have implemented singleton pattern by having a global static Store instance. I'm using a getInstance method which will return the singleton instance. When I switch the Store strategy in runtime if I call getInstance method, I'm getting the old strategy instance as an instance for the store already exists. If I assign null to that instance or forcefully create a new instance, it works well but my Senior Dev told me that it's bad design and it should not be handled like this. Any pointers on how I can proceed?

Basic Code Outline:


public interface Store {

        static Store getStore() {

       return AbstractStore.getStore();

         }

}

public abstract class AbstractStore implements Store {

        private static volatile Store store;

        public static Store getThreatStore() {

                if (store == null) {         

                        //create store instance

                }

          return store;

         }

}

public class Store1 extends AbstractStore {

}


public class Store2 extends AbstractStore {

}

Under review

Hi!

I'm not sure why do you need a Singleton here, most likely to get a way to access the store instance globally. If so, have you considered separating this "accessor" and the actual store functionality into separate classes? This way you won't have to create subclasses of the singleton, which is indeed not convenient. Instead, the Singleton class can act as context for the strategy classes.

Hi, thanks for the reply,
I would like to provide a few extra information about the current implementation. I have kept the Store as a singleton as I want all the data(At most 500MB) to be in only one store at a time and I'll be migrating this data when the strategy is switched. When creating an instance, I'm using an Object Factory to create the instance for the current store implementation which is fetched from XML / DB. I'm afraid that the Singleton Abstract class with subclasses of various strategy is fixed and I have to work around that. 

In other words, you would have a single Store class (Singleton), and a hierarchy of StoreStrategy (for a lack of better name) classes.

What are the negative sides of the current design apart from your Senior Dev criticism? Do you find it good enough?

+1

Because if it suites your needs and it works, I personally would have left it as it is and only attempt to make the changes when something in the app changes and affects these Store classes so that you have a strong reason to refactor the whole thing.

Thanks, I'll discuss with him. I don't see any option to mark this question as answered, can you close it?