前言
享元模式通过共享对象来减少内存使用和提高性能。
代码
public abstract class Flyweight
{
public abstract void Control();
}
public class ComputerFlyweight : Flyweight
{
private string _operator;
public ComputerFlyweight(string name)
{
_operator = name;
}
public override void Control()
{
Console.WriteLine($"current computer operator is :{_operator}");
}
}
public class FlyweightFactory
{
private Dictionary<string, Flyweight> flyweights = new Dictionary<string, Flyweight>();
public Flyweight GetFlyweight(string key)
{
if (flyweights.ContainsKey(key))
{
return flyweights[key];
}
else
{
Flyweight flyweight = new ComputerFlyweight(key);
flyweights.Add(key,flyweight);
return flyweight;
}
}
}
/*
* 结构型模式:Structural Pattern
* 享元模式:Flyweight Pattern
*/
internal class Program
{
static void Main(string[] args)
{
FlyweightFactory factory = new FlyweightFactory();
Flyweight userA = factory.GetFlyweight("UserA");
userA.Control();
Flyweight userB = factory.GetFlyweight("UserB");
userB.Control();
Flyweight userC = factory.GetFlyweight("UserA");
userC.Control();
Console.ReadLine();
}
}