码迷,mamicode.com
首页 > 编程语言 > 详细

简单工厂模式(C++)

时间:2016-03-26 12:35:01      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
using namespace std;

class Fruit
{
public :
    virtual void  getFruit() = 0;
};

class Banana :public Fruit
{
public :
    virtual void getFruit()
    {
        printf("我是香蕉");
    }
};
class Apple :public Fruit
{
public:
    virtual void getFruit()
    {
        printf("我是苹果");
    }
};

class  Factory
{
public:
    Fruit *create(char *p)
    {
        if (strcmp(p, "banana") == 0)
        {
            return new Banana;
        }
        else if (strcmp(p, "Apple") == 0)
        {
            return new Apple;
        }
        else
        {
            return NULL;
        }
    }

};

void main()
{
    Factory *fact=new Factory;
    Fruit *fru;
    fru=fact->create("banana");
    fru->getFruit();
    fru = fact->create("Apple");
    fru->getFruit();
}

 

简单工厂模式(C++)

标签:

原文地址:http://www.cnblogs.com/GIScore/p/5322420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!