DesignPattern/12.FlyweightPattern/2.Code/FlyweightPattern.h

90 lines
1.5 KiB
C
Raw Normal View History

2019-10-27 07:58:03 +00:00
#ifndef __FLYPATTERN_PATTERN_H__
#define __FLYPATTERN_PATTERN_H__
#include <mutex>
#include <vector>
using namespace std;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>
class NetDevice
{
public:
NetDevice(){}
virtual ~NetDevice(){}
2019-10-27 07:58:03 +00:00
virtual string getName() = 0;
/*void print(){
printf("NetDevice :%s\n",getName().c_str());
}*/
void print(int portNum){
printf("NetDevice :%s port: %d\n", getName().c_str(), portNum);
}
};
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class Hub :public NetDevice
{
public:
Hub(){}
string getName(){
return "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>";
}
};
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>:<3A><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class Switch :public NetDevice
{
public:
Switch(){}
string getName(){
return "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>";
}
};
// <20><>Ԫ<EFBFBD><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class NetDeviceFactory
{
public:
NetDevice* getNetDevice(char ch){
if (ch == 'S'){
return devicePool[1];
}
else if (ch == 'H'){
return devicePool[0];
}
else{
printf("wrong input!\n");
}
return NULL;
}
// <20><><EFBFBD><EFBFBD>ģʽ<C4A3><CABD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ψһʵ<D2BB><CAB5>
static NetDeviceFactory* getFactory(){
if (instance == NULL){
m_mutex.lock();
if (instance == NULL){
instance = new NetDeviceFactory();
}
m_mutex.unlock();
}
return instance;
}
private:
NetDeviceFactory(){
Hub *hub = new Hub();
Switch *switcher = new Switch();
devicePool.push_back(hub);
devicePool.push_back(switcher);
}
static NetDeviceFactory* instance;
static std::mutex m_mutex;
// <20><><EFBFBD><EFBFBD><EFBFBD>أ<EFBFBD><D8A3><EFBFBD>һ<EFBFBD><D2BB>vector<6F><72><EFBFBD><EFBFBD>ʾ
vector<NetDevice*> devicePool;
};
NetDeviceFactory* NetDeviceFactory::instance = NULL;
std::mutex NetDeviceFactory::m_mutex;
#endif //__FLYPATTERN_PATTERN_H__