pdrcabrod
pdrcabrod

Reputation: 1477

Which design pattern can I use to solve this situation?

First of all, I'm using Objective-C, but this doesn't matter at all.

My situation is:

I have two different scenarios. I distinguish them by a preprocessor macro like:

#ifdef USER
    do some stuff for scenario 1
#else
    do some stuff for scenario 2

Both scenarios works with a list of items all across the application, but the difference is the way of getting those items.

In the first one I get the items by sending a request to a server.

In the second one, I get them from the local device storage.

What I have now is the second scenario implemented. I have a singleton class that returns to me the list of items by getting them from the local storage. (like a traditional database singleton)

I want to add the other scenario. Since the items can be get from any point across the app, I want this to be a singleton too.

Does it make sense to have a singleton superclass, and then two subclasses that implement the different ways of getting the items? Singleton hierarchies sound quite strange to me.

Upvotes: 1

Views: 132

Answers (2)

SomeWittyUsername
SomeWittyUsername

Reputation: 18358

That's not exactly hierarchy. The superclass you're mentioning is actually an interface for your 2 concrete classes, which can be singletons if you want. The interface is an abstract entity thus any instance-related term is irrelevant to it.

You're statically defining your program behavior by using preprocessor to do the scenario choice. If you stick to this approach and it fits your requirements, you don't need any design patterns. In your code just use the interface I mentioned above, which is a port to your statically instantiated data. If you want to have more flexibility (this sounds likely), you can do your scenario choice at runtime. In this case you may find the Strategy pattern useful for applying scenarios and Factory pattern for instancing.

Upvotes: 1

Anders Johansen
Anders Johansen

Reputation: 10455

Factory combined with Strategy.

Factory as the pattern of using another class to make your instance rather than using just a constructor. You are already doing that with your Singleton most likely.

Strategy for the ability to configure which kind of object is actually created by the factory at rutime.

Upvotes: 1

Related Questions