Suppose multiple objects of the same class should do something which takes a memory consuming resource. Which of the following approaches is recommended to define and use the resource by the objects?
- Each object create the resource in its own
- Declare one resource instance and pass it to each object
- Using a static object for the resource
Let me give an example
class Section
{
public Bitmap Page {/* set and get the page...*/}
Bitmap page = new Bitmap(600,800);
Draw(SomeThing s)
{
// Draw something on the page
}
}
// in somewhere else
foreach (Section sect in Sections)
{
sect.Draw(something);
Video.AddFrame(sect.Page);
}
Versus.
class Section
{
public Bitmap Page {/* set and get the page ...*/}
Bitmap page; // it isn't instantiated in the class
Draw(SomeThing s)
{
// Clear the page
// Draw something on it
}
}
// in somewhere else
Bitmap screen = new Bitmap(600,800); // the common resource
foreach (Section sect in Sections)
{
sect.Page = screen;
sect.Draw(something); // it clears it before drawing something on it
Video.AddFrame(screen);
}
Versus.
class Section
{
public Bitmap Page {/* set and get the page ...*/}
static Bitmap page = new Bitmap(600,800);
Draw(SomeThing s)
{
// First Clear the page
// Draw something on the page
}
}
// and in somewhere else
foreach (Section sect in Sections)
{
sect.Draw(something);
Video.AddFrame(sect.Page);
}
First I used the first approach but it consumed a lot of memory as each object in my Sections
array had a bitmap. Then I was forced to try the second approach. Is this new approach better than the former on all aspects? What is the guideline for such situations?