views:

40

answers:

2

I`m want to create an object factory in C#. I want my objects to be created only via this object factory, how to achieve this? I know how to make a simple object factory, like satic class with public methods that are creating and initializing my objects. But I need to make sure people can only create object instances via object factory, any ideas?

P.S. I don`t like to involve any reflection, just use plain OOP approach.

+1  A: 

You would have to somehow hide the implementation of the class you want the factory to create so that the only method available is to use the factory. Otherwise you cannot stop people directly creating instances of the class. Another technique would be to hide the constructors of the class if you cannot hide the class itself. Most commonly this is done (in java) through the use of private and package private classes and methods.

But consider this, it is not uncommon for a developer to need access to the class. A good example might be in unit test.

So if you cannot fully hide it, consider how you might be able to "discourage" developers from directly instantiating it, but still have it available for those times they might need to not use the factory.

Derek Clarkson
Yes, I know you can just write recommendation. But I`m interested what if I need this, isn`t there a good solution for that? I thought about your private constructor + package (private + internal in C# probably) idea. Actually you can put factory created classes and factory itself into one assembly and make constructor internal. Probably it will solve the problem. But I`m looking for other ways still.
Yaroslav Yakovlev
I don't know C#. I understand it's very similar to Java though. So I presume it has the concepts of private and package private.
Derek Clarkson
+1  A: 

Create a public interface called Widget. Then create a class called WidgetFactory with a method called newWidget(); which returns Widget. Define an additional class inside of WidgetFactory "WidgetImpl", that implements the Widget interface. This will not be accessible outside of the WidgetFactory. Implement newWidget() by creating and returning a new instance of WidgetImpl.

In other words, use an interface in conjunction with a class-scoped implementation to hide the implementation.

rob
Excellent! Really thank you! That`s the answer I was waiting for!
Yaroslav Yakovlev