工厂类---一般工厂(2)

Posted on 2018-10-08 20:04  yacbo  阅读(208)  评论(0编辑  收藏  举报

一个工厂生产一种产品

//抽象水果类Fruit

//抽象的工厂类FruitFactory

//具体的工厂类 BananaFactory PearFactory

//具体的水果  //Banana Pear

 

 

class Fruit
{
public:
    virtual void sayName()
    {
        std::cout<<"Fruit"<<std::endl;
    }
};

class FruitFactory
{
    virtual Fruit *getFruit()
    {
        std::cout<<"FruitFactory:getFruit"<<std::endl;
        return NULL;
    }
};


class Pear : public Fruit
{
public:
    virtual void sayName()
    {
        std::cout<<"我是梨子"<<std::endl;
    }
};

class Banana : public Fruit
{
public:
    virtual void sayName()
    {
        std::cout<<"我是香蕉"<<std::endl;
    }
};

//dependency
class BananaFactory : FruitFactory
{
public:
    virtual Fruit *getFruit()
    {
        return new Banana();
    }
};
//dependency
class PearFactory : FruitFactory
{
public:
    virtual Fruit *getFruit()
    {
        return new Pear();
    }
};

 

 

 

工厂模式也就是鼠标工厂是个父类,有生产鼠标这个接口。
戴尔鼠标工厂,惠普鼠标工厂继承它,可以分别生产戴尔鼠标,惠普鼠标。
生产哪种鼠标不再由参数决定,而是创建鼠标工厂时,由戴尔鼠标工厂创建
后续直接调用鼠标工厂.生产鼠标()即可

 

Copyright © 2024 yacbo
Powered by .NET 9.0 on Kubernetes