Design template for using different implementations of a class / method


Sometimes we design more than one algorithm to get the same results. For instance, I have written a class which stores my data in trees, and another class that stores roughly the same data in, say, linked lists.

I will publish an interface (abstract class) called ThingStore, and I'll subclass it to TreeThingStore and ListThingStore, each respectively using trees or linked lists.

However, since I'm publishing an abstract class, I have to have someone to decide which implementation to use (EDIT: so the caller won't care about this), and I have no problem in having this hardcoded. I have needed this more than once, but I have looked at GoF and other Design Patterns catalogues unsuccesfully. The most similar pattern is the "Strategy" one, but it achieves diverse goals.

So, is there a Design Pattern for this intent? If not, someone can create one or tell me why this should not be done (or better ways to achieve the same results)?

It's a bit odd that you would specify implementation like that. Why does your caller care how you implement a particular feature? All he should care about is that your data store stores the data correctly and not really be concerned about the underlying data structure you use. But, let's say the implementation was expressed externally as different features of the data store (one is better for lots of inserts and one is better for lots of reads for example). Then, it would be up to the caller to specify which concrete class they wanted to instantiate. As the class designer, it's a bit presumptuous for you to assume you somehow know best. :)

Given that, you could definitely wrap creation of the object into a Factory and allow your user to specify to the Factory which features are important. You could go even further and use an Inversion of Control pattern where you allow your caller to instantiate and hand you a storage mechanism to use, but that seems overkill for what you are trying to do.