From: http://blog.csdn.net/pangshaohua/article/details/38912555
Refer to a factory demo written
1. Define "abstract class of background style" and "abstract factory of background style"
1 #pragmaOnce2 /*abstract class background style*/3 classCbackgroundstyle4 {5 Public:6 Virtual voidDisplaystyle () =0;//Pure virtual function7 };8 9 Ten /*Abstract Factory background style*/ One classstylefactory A { - Public: - //Factory method, the creation process of the specific background style is done by subclasses the Virtualcbackgroundstyle* createbackgroundstylefactory () =0; - voidDisplaystyle () -{//Display Style -M_pbackgroundstyle =createbackgroundstylefactory (); +M_pbackgroundstyle->Displaystyle (); - } + A Public: at stylefactory (): M_pbackgroundstyle (NULL) - { - - } -~stylefactory () - { in if(NULL! =M_pbackgroundstyle) - { to DeleteM_pbackgroundstyle; +M_pbackgroundstyle =NULL; - } the } * $ Private:Panax Notoginseng //Save the created background style -cbackgroundstyle*M_pbackgroundstyle; the};
2. Define "trend style background class" and "trend Style factory class"
FashionStyle.h
1 //FashionStyle.h2 #pragmaOnce3 /*Trend style Background class*/4 classCfashionstyle: PublicCbackgroundstyle5 {6 Public:7Cfashionstyle (void);8~cfashionstyle (void);9 Public:Ten Virtual voidDisplaystyle (); One }; A - /*Trendy Style factory*/ - classFashionstylefactory: Publicstylefactory the { - Virtualcbackgroundstyle*createbackgroundstylefactory () - { -cbackgroundstyle* Pfashionstyle =NewCfashionstyle (); + returnPfashionstyle; - }; +};
FashionStyle.cpp
1#include"StdAfx.h"2#include"BackgroundStyle.h"3#include"FashionStyle.h"4 5Cfashionstyle::cfashionstyle (void)6 {7 }8 9 TenCfashionstyle::~cfashionstyle (void) One { A } - - voidCfashionstyle::D isplaystyle () the { -AfxMessageBox (_t ("Trendy style background")); -}
Invocation mode
1 void cloaddlldemodlg::onbnclickedbutton18 () 2 {// Factory mode 3 new fashionstylefactory (); 4 Pfactory->Displaystyle (); 5 Delete pfactory; 6 Pfactory = NULL; 7 }
The factory method pattern of C + + design mode