Class FlyweightFactory<TKey, TFlyweight>
- Namespace
- WitShells.DesignPatterns.Core
Generic Flyweight Factory that caches and reuses flyweight instances keyed by
TKey. If a flyweight for a given key already exists it is returned
directly, otherwise it is created via the supplied factory delegate and cached.
public class FlyweightFactory<TKey, TFlyweight> where TFlyweight : IFlyweight
Type Parameters
TKeyThe lookup key type (e.g. a string mesh name or an enum value).
TFlyweightThe flyweight type, must implement IFlyweight.
- Inheritance
-
FlyweightFactory<TKey, TFlyweight>
- Inherited Members
Remarks
Use this pattern when you need to render thousands of objects that share the same visual data (e.g. trees, bullets, enemies of the same type). Only one flyweight instance is kept per unique key regardless of how many objects use it.
Properties
Count
Number of unique flyweight instances currently cached.
public int Count { get; }
Property Value
Methods
GetFlyweight(TKey, Func<TFlyweight>)
Returns the cached flyweight for key.
If none exists, createFunc is called to create and cache a new one.
public TFlyweight GetFlyweight(TKey key, Func<TFlyweight> createFunc)
Parameters
keyTKeyUnique identifier for the flyweight.
createFuncFunc<TFlyweight>Factory delegate invoked only when a new flyweight is needed.
Returns
- TFlyweight