The Factory mode has two major functions:
(1), defines the interface to create objects, encapsulates the creation of objects;
(2), so that the materialized class work is deferred to the sub-class.
//Product.h#ifndef _product_h_#define_product_h_classproduct{ Public: virtual void~Product ();protected: void Product ();Private: }classConcreteproduct: Publicproduct{ Public: void Concreteproduct (); void~concreteproduct ();protected:Private:}#endif //_product_h_
// Product.cpp " Product.h " <iostream>usingnamespace std; void Product::P roduct () {} void product::~Product () {}void concreteproduct::concreteproduct () {}void concreteproduct::~concreteproduct () {}
//Factory.h#ifndef _factory_h_#define_factory_h_classProduct;classfactory{ Public: Virtual void~Factory (); VirtualProduct *createproduct () =0; protected: voidFactory ();Private:};classConcretefactory: Publicfactory{ Public: voidconcretefactory (); void~concretefactory (); Product*createproduct ();protected:Private: }#endif //_factory_h_
//Fatory.cpp#include"Factory.h"#include"Product.h"#include<iostream>using namespacestd;voidfactory::factory () {}voidfactory::~Factory () {}voidconcretefactory::concretefactory () {}voidconcretefactory::concretefactory () {}product concretefactory::createproduct () {concreteproduct cproduct=Newconcreteproduct; returnproduct;}
//main.cpp#include"Factory.h"#include"Product.h"#include<iostream>using namespacestd;intMainintargcChar*argv[]) {Factory*FAC =Newconcretefactory; Product*p = fac->createproduct (); return 0;}
Factory mode of design mode (c + +)