码迷,mamicode.com
首页 > 其他好文 > 详细

抽象工厂模式

时间:2014-06-10 11:45:14      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

工厂模式其实不是太深奥,

/*为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类*/

 

简单工厂模式就是把实例化的工作封装到一个类中

工厂方法和简单工厂的不同在于,用抽象类封装工厂类

工厂方法是抽象工厂的特例,工厂方法中生产一个产品,而抽象工厂生产一系列相关的产品。

下面是一个例子,Monkey想要吃香蕉和苹果,香蕉苹果有中国产的,还有印度产的。Monkey跟住需求去找来自中国或者印度的农民,然后农民就会收获他们国家的香蕉和苹果给猴子。Kind of silly.

抽象工厂的代码:

bubuko.com,布布扣
#include <iostream>
using namespace std;
 
//////////////////////
class Apple{
public:
    virtual void AppleSayHi() = 0;
};
class ChinaApple:public Apple{
public:
    void AppleSayHi(){
            cout<<"Hi~ I‘m an Apple from China.\n";
    }
};
class IndiaApple:public Apple{
public:
    void AppleSayHi(){
            cout<<"Hi~ I‘m an Apple from India.\n";
    }
};
 
 
class Banana{
    public:
    virtual void BananaSayHi() = 0;
};
class ChinaBanana:public Banana{
    public:     
        void BananaSayHi(){
            cout<<"Hi~ I‘m a Banana from China.\n";
        }
};
class IndiaBanana:public Banana{
    public:     
        void BananaSayHi(){
            cout<<"Hi~ I‘m a Banana from India.\n";
        }
};
 
//////////////////////
 
class Farmer{
public:
    virtual Apple* harvestApple() = 0;  
    virtual Banana* harvestBanana() = 0;
};
class ChinaFarmer:public Farmer{
public:
    Apple* harvestApple(){ return  new ChinaApple();}
    Banana* harvestBanana(){return new ChinaBanana();}
};
class IndiaFarmer:public Farmer{
public:
    Apple* harvestApple(){return new IndiaApple();}
    Banana* harvestBanana(){return new IndiaBanana();}
};
 
//////////////////////
 
class Monkey{//又要买苹果又要买香蕉的客户
public:
    Apple *apple;
    Banana *banana;
    void SayHi(){
        cout<<"Some fruits in my stomach:\n";
        apple->AppleSayHi();
        banana->BananaSayHi();
    }
    Monkey(string Country){
        Farmer *farmer;
        if (0 == Country.compare("China"))
        {   
            farmer = new ChinaFarmer();
        }
        else if (0 == Country.compare("India"))
        {
            farmer = new IndiaFarmer();
        }       
        apple = farmer->harvestApple();
        banana = farmer->harvestBanana();
    }
     
 
};
int main(){
    //测试
    Monkey monkey1("China");
    monkey1.SayHi();
     
    Monkey monkey2("India");
    monkey2.SayHi();
 
    getchar();
    return 0;
}
bubuko.com,布布扣

 代码转自:  http://www.cnblogs.com/Kelvinshere/archive/2013/03/06/2947022.html

抽象工厂模式,布布扣,bubuko.com

抽象工厂模式

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/whzlw/p/3779034.html

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