一.简单工厂模式又称静态工厂方法模式(Static Factory Method)
1.静态工厂方法统一管理对象的创建。
静态工厂方法通过传入的参数判断决定创建哪一个产品的实例,封装了对象的创建
class CNokiaSimpleFactory { public: /* 静态工厂方法 */ static CNokia * CreateNokia(string model); };
CNokia * CNokiaSimpleFactory::CreateNokia(string model) { if (model == "N96") { return new CN96(); } else if (model == "N95") { return new CN95(); } else if (model == "N85") { return new CN85(); } else if (model == "N81") { return new CN81(); } else { assert(false); } return NULL; }
CNokia * nokia = NULL; /* modeName 可以从外部XML文件中读取,运行过程中动态的 决定该创建哪一种型号的手机 */string modeName = "N96"; nokia = CNokiaSimpleFactory::CreateNokia(modeName); nokia->MakeCall("123456789"); return 0;