c_cpp C ++抽象工厂
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C ++抽象工厂相关的知识,希望对你有一定的参考价值。
#include <string>
#include <iostream>
/* Common utility */
bool icompare_pred(unsigned char a, unsigned char b)
{
return std::tolower(a) == std::tolower(b);
}
bool icompare(std::string const& a, std::string const& b)
{
if (a.length()==b.length()) {
return std::equal(b.begin(), b.end(),
a.begin(), icompare_pred);
}
else {
return false;
}
}
/* Base code for car factory */
class ICar
{
public:
virtual std::string GetModel() = 0;
virtual std::string GetMaker() = 0;
};
class ICarFactory
{
public:
virtual ICar* GetRacingCar() = 0;
virtual ICar* GetSedan() = 0;
virtual ICar* GetHatch() = 0;
};
/* Holden and its car range*/
namespace Holden
{
class IHoldenCar
{
public:
virtual std::string GetModel() = 0;
virtual std::string GetMaker()
{
return "Holden";
}
};
}
namespace Holden
{
class CCommodore : public IHoldenCar
{
public:
std::string GetModel()
{
return std::string("Commodore");
}
};
}
namespace Holden
{
class CBarina : public IHoldenCar
{
public:
std::string GetModel()
{
return std::string("Barina");
}
};
}
namespace Holden
{
class CMonaro : public IHoldenCar
{
public:
std::string GetModel()
{
return std::string("Monaro");
}
};
}
/* Ford and its car range*/
namespace Ford
{
class IFordCar
{
public:
virtual std::string GetModel() = 0;
virtual std::string GetMaker()
{
return "Ford";
}
};
}
namespace Ford
{
class CBaddGT : public IFordCar
{
public:
std::string GetModel()
{
return std::string("Badd GT");
}
};
}
namespace Ford
{
class CFalcon : public IFordCar
{
public:
std::string GetModel()
{
return std::string("Falcon");
}
};
}
namespace Ford
{
class CFocus : public IFordCar
{
public:
std::string GetModel()
{
return std::string("Focus");
}
};
}
/* Holden car factory */
class CHoldenCarFactory : public ICarFactory
{
public:
ICar* GetRacingCar()
{
return (ICar*)(new Holden::CMonaro());
}
ICar* GetSedan()
{
return (ICar*)(new Holden::CCommodore());
}
ICar* GetHatch()
{
return (ICar*)(new Holden::CBarina());
}
};
/* Ford car factory */
class CFordCarFactory : public ICarFactory
{
public:
ICar* GetRacingCar()
{
return (ICar*)(new Ford::CBaddGT());
}
ICar* GetSedan()
{
return (ICar*)(new Ford::CFalcon());
}
ICar* GetHatch()
{
return (ICar*)(new Ford::CFocus());
}
};
/* Abstract factory */
class CAbstractFactory
{
public:
ICarFactory* GetCarFactory(std::string choice)
{
if (icompare(choice, "Ford"))
return (ICarFactory*)(new CFordCarFactory());
else if (icompare(choice, "Holden"))
return (ICarFactory*)(new CHoldenCarFactory());
}
};
int main(void)
{
CAbstractFactory kAbstractFactory;
ICarFactory* pkFactory = kAbstractFactory.GetCarFactory("Holden");
ICar* pkRacing = pkFactory->GetSedan();
std::cout << pkRacing->GetMaker() << "\n" <<
pkRacing->GetModel() << " " << std::endl;
return 0;
}
以上是关于c_cpp C ++抽象工厂的主要内容,如果未能解决你的问题,请参考以下文章