Class GenericSingleFactory<TKey, TProduct>
- Namespace
- WitShells.DesignPatterns.Core
Abstract Singleton-per-key Factory that creates at most one instance of
TProduct per TKey.
On the first call to Get(TKey) for a given key the creator is invoked and the
result is cached. Subsequent calls return the cached instance.
public abstract class GenericSingleFactory<TKey, TProduct>
Type Parameters
TKeyThe lookup key type.
TProductThe product type returned by the factory.
- Inheritance
-
GenericSingleFactory<TKey, TProduct>
- Inherited Members
Remarks
Typical use-case: per-type managers, per-level configurations, or any resource that should be created lazily and then reused. Subclass to expose a typed public API.
Methods
Get(TKey)
Returns the cached instance for key, creating it on first access.
public TProduct Get(TKey key)
Parameters
keyTKeyThe key to look up.
Returns
- TProduct
The single instance associated with this key.
Exceptions
- KeyNotFoundException
Thrown when no creator has been registered for
key.
IsRegistered(TKey)
Returns true if a creator has been registered for the given key.
public bool IsRegistered(TKey key)
Parameters
keyTKey
Returns
Register(TKey, Func<TProduct>)
Registers (or replaces) the creator delegate for key.
public void Register(TKey key, Func<TProduct> creator)
Parameters
keyTKeyThe key to associate with this creator.
creatorFunc<TProduct>A delegate invoked the first time this key is requested.