下面通过手机生产的过程进行理解:
#include <stdio.h>
typedef enum productType
{
xiaomi,
iphone,
huawei
}PRODUCTTYPE;
class Phone
{
public:
virtual void MakePhone() = 0;
};
class MI : public Phone
{
public:
void MakePhone()
{
printf("make xiaomi phone\n");
}
};
class IPHONE : public Phone
{
public:
void MakePhone()
{
printf("make iphone phone\n");
}
};
class HUAWEI : public Phone
{
public:
void MakePhone()
{
printf("make huawei phone\n");
}
};
class SimpleFactory
{
public:
Phone *createPhone(PRODUCTTYPE type)
{
switch (type)
{
case xiaomi:
return new MI();
case iphone:
return new IPHONE();
case huawei:
return new HUAWEI();
default:
return NULL;
}
}
};
int main()
{
SimpleFactory *factory = new SimpleFactory();
Phone *phone1 = factory->createPhone(huawei);
if (phone1 != NULL)
phone1->MakePhone();
Phone *phone2 = factory->createPhone(xiaomi);
if (phone2 != NULL)
phone2->MakePhone();
Phone *phone3 = factory->createPhone(iphone);
if (phone3 != NULL)
phone3->MakePhone();
delete phone1;
phone1 = NULL;
delete phone2;
phone2 = NULL;
delete phone3;
phone3 = NULL;
return 0;
}