Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Use the Factory Pattern to Facilitate Dynamic Typing

An abstract base class from which concrete classes are derived is a very common idiom in object-oriented code. So common indeed that a special design pattern called Factory was devised to simplify the runtime creation of derived objects. Learn how Factory can boost your code's reliability and performance.


advertisement

ood old object-oriented programming is still alive and kicking. In many C++ frameworks and applications where inheritance and virtual functions thrive you often need to create a derived object whose precise type can only be determined at runtime. Lean how Factory can boost your code's reliability and performance.


Your application has to create a derived object but the exact type of that object isn't known at compile-time. How do you implement a generic mechanism that creates the right type of object at runtime?


Use the Factory design pattern.

Spitting Images

Suppose you have an abstract class from which concrete classes are derived:




class Image //abstract
{
public:
 virtual void image_type() const=0;
 virtual ~Image()=default;
 //...
};

class JpgImage: public Image
{
public:
 virtual void image_type() const {cout<<"jpg image"<<endl;}
};

class BmpImage: public Image
{
public:
 virtual void image_type() const {cout<<"bmp image"<<endl;}
};

class PngImage: public Image
{
public:
 virtual void image_type() const {cout<<"png image"<<endl;}
};

The only feature that needs to be explained is the =default specifier in the base class' destructor. Put simply, this specifier rids you of the burden (and potential performance overhead) of defining a manual empty destructor for the abstract base class, while still ensuring that the destructor is virtual (read more on defaulted functions here).

Next, assume that you're designing an image viewer that handles various image formats: .bmp, .jpeg, .png, and so on. The viewer can determine only at runtime which derived object it needs in order to display and edit the image that the user has selected. To do that, the viewer needs an engine (known as a factory) that creates the right type of object according to the file extension. For example, when the user clicks on an image with the .jpg extension the factory will create a JpgImageobject to handle this format.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap