创作背景:各位朋友,我们继续学习C#的编程模式,本文主要介绍享元模式。享元模式是一种结构型设计模式,它主要用于减少创建对象的数量,从而提高程序性能。它通过共享对象的方式来减少内存的使用,特别是系统中有大量相似对象的时候,这种模式尤其有效。
享元模式的主要组成部分如下:
1、享元对象:享元对象就是被共享的对象,包含很多内部状态,这些状态通常是不变的。
2、享元工厂:负责创建和管理享元对象。
3、非共享状态:每个享元对象的共享状态是特定的,不会被共享。
示例代码如下:
1、创建享元接口。
/// <summary>
/// 享元对象接口
/// </summary>
public abstract class Flyweight
{
/// <summary>
/// 相关操作
/// </summary>
/// <param name="strName">名称</param>
public abstract string Operation(string strName);
}
2、实现共享享元对象。
/// <summary>
/// 实际的享元类(共享状态)
/// </summary>
public class ActualFlyweight : Flyweight
{
/// <summary>
/// 相关操作
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public override string Operation(string strName)
{
return "创建了ActualFlyweight,名称为:" + strName;
}
}
3、创建非共享享元对象。
/// <summary>
/// 实际的享元类(非共享)
/// </summary>
public class UnsharedActualFlyweight : Flyweight
{
/// <summary>
/// 相关操作
/// </summary>
/// <param name="strName"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public override string Operation(string strName)
{
return "创建了UnsharedActualFlyweight,名称为:" + strName;
}
}
4、创建享元工厂。
/// <summary>
/// 享元工厂
/// </summary>
public class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
/// <summary>
/// 构造函数
/// </summary>
public FlyweightFactory()
{
flyweights.Add("One", new ActualFlyweight());
flyweights.Add("Two", new ActualFlyweight());
flyweights.Add("Three", new ActualFlyweight());
}
/// <summary>
/// 获取Hashtable中的一个享元
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public Flyweight GetFlyweight(string key)
{
return ((Flyweight)flyweights[key]);
}
}
5、客户端调用。
/// <summary>
/// 享元模式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_flyweight_Click(object sender, EventArgs e)
{
FlyweightFactory factory = new FlyweightFactory();
Flyweight fx = factory.GetFlyweight("One");
tbox_flyweight.Text = fx.Operation("One");
Flyweight fy = factory.GetFlyweight("Two");
tbox_flyweight.Text += "\r\n" + fy.Operation("Two");
Flyweight fz = factory.GetFlyweight("Three");
tbox_flyweight.Text += "\r\n" + fz.Operation("Three");
UnsharedActualFlyweight fu = new UnsharedActualFlyweight();
tbox_flyweight.Text += "\r\n" + fu.Operation("Four");
}
6、运行结果图片。
以上就是全部享元模式的一个简单示例程序,希望对各位小伙伴能有个帮助。