C++版“简单工厂模式”实例代码
#include <iostream>
using namespace std;const int apple_size = 10;
const int banana_size = 20;
//********************************fruit interface
class fruit
{
public:
virtual void name()=0;
virtual int size()=0;
//virtual ~fruit();
};
//**********************************apple instance
class apple : public fruit
{
public:
void name();
int size();
};void apple::name()
{
cout<<"apple\n";
}int apple::size()
{
return apple_size;
}
//*********************************banana instance
class banana : public fruit
{
public:
void name();
int size();
};void banana::name()
{
cout<<"banana\n";
}int banana::size()
{
return banana_size;
}
//**********************************fruit factory
class garden
{
public:
static fruit* produce_apple()
{
return new apple();
}static fruit* produce_banana()
{
return new banana();
}
};
int main()
{
fruit* ap,* ba;
ap = garden::produce_apple();
ba = garden::produce_banana();
ap->name();
ba->name();
return 0;
}