views:

115

answers:

4

When my application starts up it needs to get an instance of the correct DAL class (currently there are 4) based on what user is logged in. Certain users are pulling down from certain databases.

Is it still considered a "factory" pattern if instead of instantiating instances of those DAL classes, I simply return the correct static instance of it? I have no need to continually create these objects since all users can share them.

Psuedocode:

public class RepositoryFactory
{
    public static IRepository repoA = new FranksLumberRepo();
    public static IRepository repoB = new LowesHardwareRepo();
    public static IRepository repoC = new HackmansHardwareRepo();
    public static IRepository repoD = new TomsHardwareRepo();

    public IRepository createRepo(User currentUser)
    {
        switch(User.Store)
        {
             case FrankLumber:
                  return repoA;
             case LowesHardware:
                  return repoB;
             case Hackmans:
                  return repoC;
             case TomsHardware:
                  return repoD;
             default:
                  throw exception;
        }

    }
}
+2  A: 

This would be a case of an "Abstract Factory" pattern, actually.

McWafflestix
This is a good example of a when you could use an Abstract Factory pattern.
David Yancey
After reading Wikipedias page on Abstract Factory Pattern, it would seem an Abstract Factory is used for returning a sub-factory itself, which can then be used to instantiate objects. This isn't the case with the code above, right?
Simucal
There is no AbstractFactory in the example. Where is the Abstract and where is the concrete factory?
TimW
+1  A: 

The factory pattern is essentially an abstraction (in the general sense of the term). Even if you return the static objects you are still adding a layer of abstraction, which is good and should be considered a part of the factory pattern in general.

tathagatac
A: 

This would be a singleton factory.

Gerald
+1 for a nice term :)
Aamir
+4  A: 

Slight clarification on your terminology. The objects are not static just the references. The objects are instances which have at least one static reference. When you return the object you are returning simply a reference to that object. It has no idea that there is a static holding it in some other area.

But yes, this is a valid factory pattern.

JaredPar