What is the difference between Activator.CreateInstance
and factory? Can they be used interchangeably? Or stil do we need a fac开发者_开发百科tory pattern?
Activator.CreateInstance
is a static method that creates an instance of the specified type using that type's default constructor.
While factory pattern deals with the problem of creating objects (products) without specifying the exact class of object that will be created.
You can "use" the Activator.CreateInstance
within a factory pattern to return different types of objects. See this example. You can also create a generic factory utilizing Activator.CreateInstance
The factory pattern is a higher-level pattern. It gives you a structure in which you can address some issues that can occur with object creation. To quote from Wikipedia,
The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns.
Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized build-up and tear-down concerns of the object.
Activator.CreateInstance doesn't address any of these issues, it merely allows you to create a new instance of a type. If you don't have issues like the above (and many uses of the "factory pattern" aren't in the context of such issues), Activator.CreateInstance will be fine.
精彩评论