RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Use the Factory Pattern to Facilitate Dynamic Typing-2 : Page 2

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.


Factory Class

Factory is implemented as an independent class with a static member function called create(). create() returns a pointer whose static type is that of the abstract base class. The dynamic typeof the returned pointer will reflect the actual object that has been created for viewing the image:

class ImageFactory 
  static Image* create(const std::string& ext) 
      if (ext=="jpg")
         return new JpgImage;
      else if (ext=="bmp")
         return new BmpIamge;
      else //default 
         return new PngImage;


Technically, you don't need to instantiate an ImageFactory object to call create() because it's a static member function. However, for the sake of an intuitive and cleaner syntax, you can still create a factory object, as shown in the following code listing. Additionally, it's best to use a smart pointer to ensure automatic cleanup of object created by the factory class. Smart pointers such as std::tr1::shared_ptr, std::auto_ptr, and its successor, std::unique_ptr, also offer the convenience of the member function reset()which disposes of an image object and binds a new object to the same smart pointer in one shot:

int main()
  ImageFactory factory;
  std::auto_ptr<const Image> img(factory.create("jpg"));
  img->image_type(); //output: "jpg image"

  img->image_type();//output: "bmp image"

  img.reset(factory.create("")); //default
  img->image_type(); //output: "png image"


Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date