开发者

Object factory implementation

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 us开发者_StackOverflow社区e plain OOP approach.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜