What Is a Design Pattern?


Four Essential Elements


Creational Design Patterns


Singleton

Solution 1


Graphics.h looks like the following:

class Graphics

{

public:

Graphics ();

~Graphics ();

};


// in a comment, place the following:

// make sure to instantiate only one of these!

extern Graphics theGraphics;



Solution 2


Graphics.h looks like this:

class Graphics

{

public:

static void DrawRect ();

static void DrawCircle ();

static void DrawBitmap ();

};

and code like this:

Graphics::DrawRect ();


class WindowsGraphics : public Graphics

{

public:

static void DrawRect (); // error!

static void DrawCircle (); // error!

static void DrawBitmap (); // error!

};


Solution 3




Graphics.h looks like this:


class Graphics

{

public:

static Graphics *MakeInstance ();


protected:

Graphics (); // the world can’t make them at will

static Graphics *instance;

};



Graphics.cpp looks like this:

Graphics *Graphics::instance = 0 ;


Graphics *

Graphics::MakeInstance ()

{

if (NULL == instance)

instance = new Graphics;


return instance;

}



code looks like this,

for every place that wants to use Graphics:

Graphics *gPtr = Graphics::MakeInstance ();


One Ramification


Graphics

Graphics::MakeInstance ()

{

switch (someValue)

{

case WINDOWS:

instance = new WIndowsGraphics;

break;


default:

instance = new Graphics;

break;

}

return instance;

}


Consequences


Summary