Flyweight Factory (CharacterFactory):?
Short answer: The CharacterFactory is responsible for managing the flyweights. It keeps track of the existing character objects and ensures that no duplicate instances of the same character are created. If a character already exists in the dictionary, it is reused. Otherwise, a new Character object is created and stored for future use. public class CharacterFactory
Example code
{
private readonly Dictionary<char, Character> _characters = new
Dictionary<char, Character>();
public Character GetCharacter(char symbol)
{
if (!_characters.ContainsKey(symbol))
{
_characters[symbol] = new Character(symbol);
}
return _characters[symbol];
}
}
Real-world example (ShopNest)
ShopNest’s NotificationFactory creates Email or SMS senders based on user preference.
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png