c++设计模式--简单工厂模式

来源:互联网 发布:windows命令行列出文件 编辑:程序博客网 时间:2024/06/06 23:17

// SimpleFactoryPattern.cpp : 定义控制台应用程序的入口点。
//通过此例程了解设计模式里的“简单工厂模式”

#include "stdafx.h"#include <stdlib.h>#include <string>#include <iostream>using namespace std;//图形抽象类class CShape{public: CShape() { } virtual ~CShape() { }public: virtual void Show() const=0;};   class CRectangle:public CShape{public: CRectangle() { } ~CRectangle() { }public: void Show() const {  cout<<"我是矩形"<<endl; }};   class CEllipes:public CShape{public: CEllipes() { } ~CEllipes() { }public: void Show() const {  cout<<"我是圆"<<endl; }};   class CSimpleFactory{public: CSimpleFactory() { } ~CSimpleFactory() { }public: static CShape* CreateShape(const string strName) {  if (strName=="矩形")  {   return new CRectangle();  }  if (strName=="圆")  {   return new CEllipes();  }  return NULL; }};   int _tmain(int argc, _TCHAR* argv[]){ cout<<"--------------简单工厂模式测试案例----------------------"<<endl;  CShape *pShape=NULL; pShape=CSimpleFactory::CreateShape("矩形"); pShape->Show(); cout<<endl<<endl; delete pShape; pShape=NULL; pShape=CSimpleFactory::CreateShape("圆"); pShape->Show(); delete pShape; pShape=NULL; system("pause"); return 0;}


 

原创粉丝点击