原文地址:
http://www.cnblogs.com/hebaichuanyeah/p/5459869.html
工厂模式是指,定义一个创建对象的类(factory),利用这个来实例化指定子类。
1.简单工厂模式
例子,假如有一个code代码类,java,C#,C艹等等是该类的子类,通过codeFactory来实例化子类。并在子类中重写virtual函数print。
注:C艹中,如果用父类的指针释放子类的资源,并且父类中的析构函数不是virtual函数,那么子类的析构函数不会调用,子类的资源不会释放,从而造成内存泄露。
#include "iostream" using namespace std; class Code { public : Code(){}; virtual void print(string str)=0; virtual ~Code(){}; }; class CSharp : public Code { public : CSharp(){} void print(string str) { cout<<"Console.WriteLine(\""<<str<<"\");"<<endl; } }; class CFuck : public Code { public : CFuck(){} void print(string str) { cout<<"cout<<(\""<<str<<"\");"<<endl; } }; class CProgram : public Code { public : CProgram(){} void print(string str) { cout<<"printf(\""<<str<<"\");"<<endl; } }; class Java :public Code { public : Java(){} void print(string str) { cout<<"System.out.printf(\""<<str<<"\");"<<endl; } }; class CodeFactory { public : Code * createWhatCode(string name) { if(name == "CSharp") return new CSharp(); if(name == "Java") return new Java(); if(name == "CProgram") return new CProgram(); if(name == "CFuck") return new CFuck(); } }; main() { CodeFactory factory; string programName[4]={"CSharp","CProgram","CFuck","Java"}; for(int i=0;i<4;i++) { Code * code = factory.createWhatCode(programName[i]); code->print("hello world"); delete code; } }
运行结果
时间: 2024-11-03 05:20:51