Class GenericFactory<TKey, TProduct>
- Namespace
- WitShells.DesignPatterns.Core
A generic, key-based Factory that creates new product instances on demand. Creator delegates are registered once and called every time a new object is needed, so each call to Create(TKey) returns a fresh instance.
public class GenericFactory<TKey, TProduct>
Type Parameters
TKeyThe lookup key type (e.g. a string, enum, or int).
TProductThe base type or interface of the objects being created.
- Inheritance
-
GenericFactory<TKey, TProduct>
- Inherited Members
Examples
var factory = new GenericFactory<string, IWeapon>();
factory.Register("sword", () => new Sword());
factory.Register("bow", () => new Bow());
IWeapon weapon = factory.Create("sword");
Remarks
Use GenericSingleFactory<TKey, TProduct> instead when you want exactly one instance per key (singleton-per-key semantics).
Methods
Create(TKey)
Creates and returns a new product for the given key by invoking its registered creator.
public TProduct Create(TKey key)
Parameters
keyTKeyThe key whose creator should be invoked.
Returns
- TProduct
A new instance of the product.
Exceptions
- ArgumentException
Thrown when no creator has been registered for
key.
Register(TKey, Func<TProduct>)
Registers a creator delegate for the given key. If the key is already registered the call is silently ignored.
public void Register(TKey key, Func<TProduct> creator)
Parameters
keyTKeyThe key to associate with the creator.
creatorFunc<TProduct>A delegate that returns a new product instance.