字体 享元
public class FontFlyWeight
{
//享元对象标识,用于作为存入键值对中的键值
public const string NAME = "";
private char fontContent;
public char FontContent
{
get => fontContent;
set => fontContent = value;
}
public FontFlyWeight(char font)
{
fontContent = font;
}
public string SetColor(string color)
{
Console.WriteLine($"将当前字体{FontContent}的字体颜色设置为{color}");
return color;
}
public string SetSize(string size)
{
Console.WriteLine($"将当前字体{FontContent}的字体大小设置为{size}");
return size;
}
}
public class FontA : FontFlyWeight
{
public new const string NAME = "FontA";
public FontA(char font) : base(font)
{
}
}
public class FontB : FontFlyWeight
{
public new const string NAME = "FontB";
public FontB(char font) : base(font)
{
}
}
public class FontFactory
{
private static FontFactory m_instance;
public static FontFactory GetInstance
{
get
{
if (m_instance == null)
{
m_instance = new FontFactory();
}
return m_instance;
}
}
private FontFactory()
{
AddFont(FontA.NAME, new FontA('a'));
AddFont(FontB.NAME, new FontB('b'));
}
private Dictionary<string, FontFlyWeight> m_fontDic =
new Dictionary<string, FontFlyWeight>();
public void AddFont(string fontName, FontFlyWeight font)
{
if (m_fontDic.ContainsKey(fontName))
{
m_fontDic[fontName] = font;
}
else
{
m_fontDic.Add(fontName, font);
}
}
public FontFlyWeight FindFont(string fontName)
{
if (m_fontDic.ContainsKey(fontName))
{
return m_fontDic[fontName];
}
return null;
}
public void RemoveFont(string fontName)
{
if (m_fontDic.ContainsKey(fontName))
{
m_fontDic.Remove(fontName);
}
}
}
static void Main(string[] args)
{
FontFlyWeight a, b;
a = FontFactory.GetInstance.FindFont(FontA.NAME);
var aa = FontFactory.GetInstance.FindFont(FontA.NAME);
if (a.GetHashCode().Equals(aa.GetHashCode()))
{
Console.WriteLine("相同对象");
}
}
}