标签:
来自:http://blog.csdn.net/pangshaohua/article/details/38912555
参考写的一个工厂demo
1、定义"背景风格的抽象类"、"背景风格的抽象工厂"
1 #pragma once 2 /*背景风格抽象类*/ 3 class CBackgroundStyle 4 { 5 public: 6 virtual void DisplayStyle() = 0;//纯虚函数 7 }; 8 9 10 /*背景风格抽象工厂 */ 11 class StyleFactory 12 { 13 public: 14 //工厂方法,具体背景风格的创建过程由子类完成 15 virtual CBackgroundStyle* CreateBackgroundStyleFactory() = 0; 16 void DisplayStyle() 17 {//显示风格 18 m_pBackgroundStyle = CreateBackgroundStyleFactory(); 19 m_pBackgroundStyle->DisplayStyle(); 20 } 21 22 public: 23 StyleFactory():m_pBackgroundStyle(NULL) 24 { 25 26 } 27 ~StyleFactory() 28 { 29 if(NULL != m_pBackgroundStyle) 30 { 31 delete m_pBackgroundStyle; 32 m_pBackgroundStyle = NULL; 33 } 34 } 35 36 private: 37 //保存创建的背景风格 38 CBackgroundStyle* m_pBackgroundStyle; 39 };
2、定义"潮流风格背景类"、"潮流风格工厂类"
//FashionStyle.h
1 //FashionStyle.h 2 #pragma once 3 /*潮流风格背景类 */ 4 class CFashionStyle: public CBackgroundStyle 5 { 6 public: 7 CFashionStyle(void); 8 ~CFashionStyle(void); 9 public: 10 virtual void DisplayStyle(); 11 }; 12 13 /*潮流风格工厂*/ 14 class FashionStyleFactory: public StyleFactory 15 { 16 virtual CBackgroundStyle* CreateBackgroundStyleFactory() 17 { 18 CBackgroundStyle* pFashionStyle = new CFashionStyle(); 19 return pFashionStyle; 20 }; 21 };
FashionStyle.cpp
1 #include "StdAfx.h" 2 #include "BackgroundStyle.h" 3 #include "FashionStyle.h" 4 5 CFashionStyle::CFashionStyle(void) 6 { 7 } 8 9 10 CFashionStyle::~CFashionStyle(void) 11 { 12 } 13 14 void CFashionStyle::DisplayStyle() 15 { 16 AfxMessageBox(_T("潮流风格背景")); 17 }
//调用方式
1 void CLoadDllDemoDlg::OnBnClickedButton18() 2 {//工厂模式 3 StyleFactory* pFactory = new FashionStyleFactory(); 4 pFactory->DisplayStyle(); 5 delete pFactory; 6 pFactory = NULL; 7 }
上图
标签:
原文地址:http://www.cnblogs.com/lpxblog/p/4607816.html