标签:span 型号 int factory 成员 模拟 app cout ring
简单工厂模式
主要用于创建对象。 新加入类时。 不会影响曾经的系统代码。
核心思想是用一个工厂来依据输入的条件产生不同的类,然后依据不同类的 virtual 函数得到不同的结果.
以下以苹果手机的生产为例。模拟手机生产工厂。
苹果手机有各种不同的型号,有Iphone4、Iphone4s、Iphone5等等。
我们通过一个工厂来生产,client依据客户的需求生产不同型号的手机。
代码例如以下:
Apple.h
#pragma once #include <iostream> class Apple { public: Apple(); virtual ~Apple(); virtual void ShowVersion() = 0; virtual void MakeCall(const std::string &num) = 0; };
#include "Apple.h" Apple::Apple() { } Apple::~Apple() { }
Apple4.h
#pragma once #include "Apple.h" class Apple4 : public Apple { public: Apple4(); ~Apple4(); virtual void ShowVersion(); virtual void MakeCall(const std::string &num); };
#include "Apple4.h" #include <iostream> #include <string> using namespace std; Apple4::Apple4() { cout << "Apple4 Created!" << endl; } Apple4::~Apple4() { }; void Apple4::ShowVersion() { cout << "I‘m Apple4" << endl; } void Apple4::MakeCall(const std::string &num) { cout << "I‘m Call num :" << num << endl; }
#pragma once #include "Apple.h" class Apple4s : public Apple { public: Apple4s(); ~Apple4s(); virtual void ShowVersion(); virtual void MakeCall(const std::string &num); };
#include "Apple4s.h" #include <iostream> #include <string> using namespace std; Apple4s::Apple4s() { cout << "Apple4s Created!" << endl; } Apple4s::~Apple4s() { }; void Apple4s::ShowVersion() { cout << "I‘m Apple4s" << endl; } void Apple4s::MakeCall(const std::string &num) { cout << "I‘m Call num :" << num << endl; }
#pragma once #include "Apple.h" #include <string> class AppleFactory { public: AppleFactory(); ~AppleFactory(); static Apple * MakePhone(const std::string &version);//声明为静态成员函数 };
#include "AppleFactory.h" #include "Apple4.h" #include "Apple4s.h" #include <iostream> #include <string> AppleFactory::AppleFactory() { } AppleFactory::~AppleFactory() { } Apple * AppleFactory::MakePhone(const std::string &version) { if(version == "Apple4") { return new Apple4(); } if(version == "Apple4s") { return new Apple4s(); } return NULL; }
#include "AppleFactory.h" #include <iostream> int main() { Apple * A4 = AppleFactory::MakePhone("Apple4"); A4->ShowVersion(); A4->MakeCall("10086"); std::cout << "------------------" << std::endl; Apple * A4s = AppleFactory::MakePhone("Apple4s"); A4s->ShowVersion(); A4s->MakeCall("10010"); return 0; } /* 执行结果: Apple4 Created! I‘m Apple4 I‘m Call num :10086 ------------------ Apple4s Created! I‘m Apple4s I‘m Call num :10010 请按随意键继续. . . */
这个模式也叫静态工厂模式,由于依赖的是工厂类中的静态方法。
标签:span 型号 int factory 成员 模拟 app cout ring
原文地址:http://www.cnblogs.com/yangykaifa/p/6883144.html