Created
March 5, 2020 04:01
-
-
Save imsjz/9f7cf872601402c29f730eca794fb60c to your computer and use it in GitHub Desktop.
简单工厂模式和工厂模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
enum PRODUCTTYPE {SFJ, XSL}; // 两种产品:舒肤佳,夏雪莲 | |
// 简单工厂模式 | |
namespace simple_factory { | |
// 抽象基类用首字母小写 | |
class soapBase{ | |
public: | |
virtual ~soapBase(){}; | |
virtual void show() = 0; | |
}; | |
class SFJSoap : public soapBase{ | |
public: | |
void show() { | |
cout << "SFJ" << endl; | |
} | |
}; | |
class XSLSoap:public soapBase{ | |
public: | |
void show() { | |
cout << "XSL" << endl; | |
} | |
}; | |
// 简单工厂 | |
class Factory{ | |
public: | |
soapBase* createSoap(PRODUCTTYPE type) { | |
switch(type){ | |
case SFJ: | |
return new SFJSoap; | |
break; | |
case XSL: | |
return new XSLSoap; | |
break; | |
} | |
} | |
}; | |
// 调用简单工厂模式 | |
void test_simpley_factory(){ | |
Factory factory; | |
soapBase* p_soap1 = factory.createSoap(SFJ); | |
p_soap1->show(); | |
soapBase* p_soap2 = factory.createSoap(XSL); | |
p_soap2->show(); | |
}; | |
} | |
// 工厂模式 | |
namespace factory { | |
// 抽象基类用首字母小写 | |
class soapBase { | |
public: | |
virtual ~soapBase(){}; | |
virtual void show() = 0; | |
}; | |
class SFJSoap : public soapBase { | |
public: | |
void show() { cout << "SFJ" << endl; } | |
}; | |
class XSLSoap : public soapBase { | |
public: | |
void show() { cout << "XSL" << endl; } | |
}; | |
// 来一个抽象工厂基类 | |
class baseFactory { | |
public: | |
virtual soapBase *createSoap() = 0; | |
}; | |
// 具体工厂 | |
class SFJFactory : baseFactory { | |
public: | |
soapBase *createSoap() { return new SFJSoap; } | |
}; | |
class XSLFactory : baseFactory { | |
public: | |
soapBase *createSoap() { return new XSLSoap; } | |
}; | |
// 调用工厂模式 | |
void test_factory() { | |
SFJFactory factory1; | |
soapBase *p_soap1 = factory1.createSoap(); | |
p_soap1->show(); | |
XSLFactory factory2; | |
soapBase *p_soap2 = factory2.createSoap(); | |
p_soap2->show(); | |
}; | |
} | |
int main() { | |
// simple_factory::test_simpley_factory(); | |
factory::test_factory(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment