Flyweight Pattern Code Review
Code Download
- Download Description:flyweight pattern download
- .NET Framework:3.5
- .NET Language:C#
- Date Published:2009-07-01
- Download Size:2,077 KB
Define the Pattern Interface and Handler Objects
Define the IFlyweight interface to be used as the "blueprint" for the main application classes.
public interface IFlyweight
{
Int32 Width { get; }
Int32 Height { get; }
void Load(String filename);
void Display(PaintEventArgs e, Int32 row, Int32 col);
}
The Flyweight class (object) inherits from the IFlyweight interface and implements the Load() and Display() methods.
public class Flyweight : IFlyweight
{
private Image m_thumbNail;
public Int32 Width { get; private set; }
public Int32 Height { get; private set; }
public void Load(string filename)
{
this.m_thumbNail = new Bitmap(filename).GetThumbnailImage(100, 100, null, new IntPtr());
this.Width = this.m_thumbNail.Width;
this.Height = this.m_thumbNail.Height;
}
public void Display(PaintEventArgs e, Int32 row, Int32 col)
{
e.Graphics.DrawImage(this.m_thumbNail, col, row, this.m_thumbNail.Width, this.m_thumbNail.Height);
}
}
The Load() method essentially takes a large object (image) and creates a smaller version of the object (thumbnail). The
Display() method provides a means to view the smaller object (thumbnail).
Define the Flyweight Factory Object
The FlyweightFactory class manages a collection of IFlyweight objects.
class FlyweightFactory
{
Dictionary<String, IFlyweight> flyweights = new Dictionary<string, IFlyweight>();
public FlyweightFactory()
{
flyweights.Clear();
}
public IFlyweight this[String index]
{
get
{
if (!flyweights.ContainsKey(index))
{
flyweights[index] = new Flyweight();
}
return (flyweights[index]);
}
}
}