《设计模式之禅(第2版)》的读书笔记,原书是用java写的,由于C++语法和java语法还是有差异的,故自己用C++实现了一遍,其中难免不会有疏漏,望大家不吝赐教。
其中的NvWa就是main方法,这里没有单独使用类。其余的都与该图相同。
Human.h
#pragma once
class Human {
public:
virtual void getColor() = 0;
virtual void talk() = 0;
virtual ~Human() {};
};
BlackHuman.h
#pragma once
#include "Human.h"
#include <iostream>
using namespace std;
class BlackHuman : public Human
{
public:
void getColor()
{
std::cout << "黑色人种的皮肤颜色是黑的!" << endl;
}
void talk()
{
std::cout << "黑人会说话,一般人听不懂" << endl;
}
};
WhiteHuman.h
#pragma once
#include "Human.h"
#include <iostream>
using namespace std;
class WhiteHuman : public Human
{
public:
void getColor()
{
std::cout << "白人种的皮肤颜色是白色的!" << endl;
}
void talk()
{
std::cout << "白色人种会说话,一般说的都是单字节。" << endl;
}
};
YellowHuman.h
#pragma once
#include "Human.h"
#include <iostream>
using namespace std;
class YellowHuman : public Human
{
public:
void getColor()
{
std::cout << "黄色人种的皮肤颜色是黄色的!" << endl;
}
void talk()
{
std::cout << "黄色人种会说话,一般说的都是双字节。" << endl;
}
};
AbstractFactory.h
#pragma once
#include <string>
#include <vector>
#include "Human.h"
class AbstractFactory
{
public:
virtual Human *createHuman(std::string somehuman) = 0;
~AbstractFactory() {}
};
HumanFactory.h
#pragma once
#include "AbstractFactory.h"
#include "Human.h"
#include "WhiteHuman.h"
#include "BlackHuman.h"
#include "YellowHuman.h"
class HumanFactory : public AbstractFactory
{
Human *createHuman(std::string somehuman) override
{
if (somehuman == "black")
{
return new BlackHuman();
}
else if (somehuman == "white")
{
return new WhiteHuman();
}
else if (somehuman == "yellow")
{
return new YellowHuman();
}
return NULL;
}
};
main.cpp文件:
#include <iostream>
#include "AbstractFactory.h"
#include "Human.h"
#include "HumanFactory.h"
int main()
{
AbstractFactory *factory = new HumanFactory();
Human *whiteHuman = factory->createHuman("white");
whiteHuman->getColor();
whiteHuman->talk();
delete whiteHuman;
std::cout << std::endl;
Human *blackHuman = factory->createHuman("black");
blackHuman->getColor();
blackHuman->talk();
delete blackHuman;
std::cout << std::endl;
Human *yellowHuman = factory->createHuman("yellow");
yellowHuman->getColor();
yellowHuman->talk();
delete factory;
delete yellowHuman;
return 0;
}
运行结果: