Flyweight享元模式
1. 简介
- 定义
- 使用共享对象可有效地支持大量的细粒度的对象。
- 解决问题
- 面向对象技术可以很好地解决一些灵活性或可扩展性问题,但在很多情况下需要在系统中增加类和对象的个数。当对象数量太多时,将导致运行代价过高,带来性能下降等问题。享元模式正是为解决这一类问题而诞生的。
- 原理
- 享元模式其实就是工厂模式的一个改进机制,享元模式同样要求创建一个或一组对象,并且就是通过工厂方法生成对象的,只不过享元模式中为工厂方法增加了缓存这一功能。
- 类图
- 典型的例子,如:string对象,Type对象等,都是使用享元模式设计。
2. 示例
/// <summary>
/// The 'Flyweight' class.
/// </summary>
public class Character
{
// intrinsic state
protected char _symbol;
protected int _size;
protected string _font;
// extrinsic state
protected Position _position;
public void Display(Position position)
{
Console.WriteLine(
String.Format("Symbol: {0} Size: {1} Font: {2} Position: {3} {4}",
_symbol, _size, _font, position._x, position._y));
}
}
/// <summary>
/// A 'ConcreteFlyweight' class
/// </summary>
public class CharacterA : Character
{
public CharacterA()
{
_symbol = 'A';
_size = 10;
_font = "宋体";
//_position = new Position(0, 1);
}
}
/// <summary>
/// The 'FlyweightFactory' class
/// </summary>
public class CharacterFactory
{
// Keeps the character object by specifying key/value.
private Dictionary<char, Character> _characters =
new Dictionary<char, Character>();
public Character this[char key]
{
get
{
Character character = null;
// Checked the character whether existed or not,
// if the character existed, then directly returns,
// otherwise, instantiates a character object.
if (_characters.ContainsKey(key))
{
character = _characters[key];
}
else
{
string name = this.GetType().Namespace + "." +
"Character" + key.ToString();
character = Activator.CreateInstance(
Type.GetType(name)) as Character;
_characters.Add(key, character);
}
return character;
}
}
}
/// <summary>
/// The client.
/// </summary>
/// <param name="args">The args.</param>
static void Main(string[] args)
{
string text = "ABZABBZZ";
char[] letters = text.ToCharArray();
var characterFactory = new CharacterFactory();
// Creates random position ranges 0 to 100.
var rd = new Random();
foreach (char c in letters)
{
Character character = characterFactory[c];
var p = new Position(rd.Next(0, 100), rd.Next(0, 100));
character.Display(p);
}
Console.ReadKey();
}
如果您认为这篇文章还不错或者有所收获,您可以通过右边的"打赏"功能 打赏我一杯咖啡【物质支持】,也可以点击左下角的【好文要顶】按钮【精神支持】,因为这两种支持都是我继续写作,分享的最大动力!
作者: 大师兄石头
来源: https://bigbrotherstone.cnblogs.com/
声明: 原创博客请在转载时保留原文链接或者在文章开头加上本人博客地址,如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能,如有特殊需求请与本人联系!