享元模式应用较少,这里举一个森林和树木的例子来说明这个模式的应用。一片森林中有成千上万棵树木,如果每棵树都创建一个对象,那么内存中的对象数量相当庞大,更何况我们现实世界中还有成千上万个森林。
public
class
App
{
public static void Main()
{
Forest forest = new Forest( " 国家森林 " );
forest.trees.Add(TreeFactory.GetTree( " 白杨 " , 5 ));
Forest forest2 = new Forest( " 自然森林 " );
forest2.trees.Add(TreeFactory.GetTree( " 白杨 " , 6 ));
forest2.trees.Add(TreeFactory.GetTree( " 白杨 " , 5 ));
if (ReferenceEquals(forest.trees[ 0 ],forest2.trees[ 1 ])) Console.WriteLine( " 内存中指的是同一棵树 " );
Console.ReadLine();
}
}
public class Tree
{
string type;
int age;
public Tree( string tType, int tAge)
{
this .type = tType;
this .age = tAge;
}
}
public static class TreeFactory
{
private static Hashtable existTrees = new Hashtable();
public static Tree GetTree( string treeType, int treeAge)
{
if ( ! existTrees.ContainsKey(treeType + treeAge))
{
existTrees.Add(treeType + treeAge, new Tree(treeType, treeAge));
}
return existTrees[treeType + treeAge] as Tree;
}
}
public class Forest
{
string name;
public List < Tree > trees { get ; set ; }
public Forest( string name)
{
this .name = name;
trees = new List < Tree > ();
}
}
{
public static void Main()
{
Forest forest = new Forest( " 国家森林 " );
forest.trees.Add(TreeFactory.GetTree( " 白杨 " , 5 ));
Forest forest2 = new Forest( " 自然森林 " );
forest2.trees.Add(TreeFactory.GetTree( " 白杨 " , 6 ));
forest2.trees.Add(TreeFactory.GetTree( " 白杨 " , 5 ));
if (ReferenceEquals(forest.trees[ 0 ],forest2.trees[ 1 ])) Console.WriteLine( " 内存中指的是同一棵树 " );
Console.ReadLine();
}
}
public class Tree
{
string type;
int age;
public Tree( string tType, int tAge)
{
this .type = tType;
this .age = tAge;
}
}
public static class TreeFactory
{
private static Hashtable existTrees = new Hashtable();
public static Tree GetTree( string treeType, int treeAge)
{
if ( ! existTrees.ContainsKey(treeType + treeAge))
{
existTrees.Add(treeType + treeAge, new Tree(treeType, treeAge));
}
return existTrees[treeType + treeAge] as Tree;
}
}
public class Forest
{
string name;
public List < Tree > trees { get ; set ; }
public Forest( string name)
{
this .name = name;
trees = new List < Tree > ();
}
}