1

I have a series of Factory objects I wish to expose trough a "root" utility (object). This root utility is in-and-of itself...a factory. As a utility object, I wish to implement it as a static class. However, isn't possible using my current design...as you cannot implement static members in an interface.

So...

MY QUESTION IS: How can I alter the classes below to get the static factory affect above?

THE CODE LOOKS LIKE:

public interface IFactory
{
    I Create<I>();

    IFactoryTransform Transformer { get; }
    IFactoryDataAccess DataAccessor { get; }
    IFactoryValidator Validator { get; }
}

public static class Factory : IFactory
{
    static Factory()
    {

        Transformer = new FactoryTransform();
        DataAccessor = new FactoryDataAccess();
        Validator = new FactoryValidator();
    }

    public I Create<I>()
    {
        var model = typeof(I);

        // Activation code will go here...

        throw new NotSupportedException("Type " + model.FullName + " is not supported.");
    }

    public IFactoryDataAccess DataAccessor { get; private set; }
    public IFactoryTransform Transformer { get; private set; }
    public IFactoryValidator Validator { get; private set; }
}
Prisoner ZERO
  • 13,848
  • 21
  • 92
  • 137
  • you can check this post http://miroprocessordev.blogspot.com/2011/12/design-patterns-series-7-singleton.html to create a singleton pattern and I think you don't have to instantiate your objects in the constructor – Amir Ismail Aug 05 '12 at 12:36

3 Answers3

4

You can move your static keyword from Factory class to one level up. For example you can have a static class Utils, where you have a singleton property MyFactory.

public static class Utils
{
    public static IFactory MyFactory {get; private set}
    static Utils()
    {  
        MyFactory = new Factory();
    }
}

//usage
var myInterface = Utils.MyFactory.Create<IMyInterfrace>()

That said, I would probably use DI instead of the factories and IoC container to manage lifetime of the objects.

oleksii
  • 35,458
  • 16
  • 93
  • 163
0

It is not possible that a static class is inheriting from an interface. I think what you really want is a singleton lifecycle factory.

Rookian
  • 19,841
  • 28
  • 110
  • 180
0

why don't use Microsoft unity and dependency injection it is a better practice than manage yourself a static factory: http://msdn.microsoft.com/en-us/library/ff649614.aspx it will be unity framework that will instantiate for you all object

IUnityContainer myContainer = new UnityContainer();
FactoryDataAccess da= new FactoryDataAccess();
myContainer.RegisterInstance<IFactoryDataAccess >(da);

when you call it, it will use FactoryDataAccess instance :

IFactoryDataAccess myServiceInstance = myContainer.Resolve<IFactoryDataAccess >();
Hassan Boutougha
  • 3,871
  • 1
  • 17
  • 17