面向对象的思想设计榨汁机的类

榨汁机的特点是放入苹果得苹果汁,放入香蕉得香蕉汁,而具体制作的过程并不关心。

#include <iostream>
#include <string>
using namespace std;

typedef enum{//枚举水果
    apple,
    banana,
    orange,
    nothing
}Fruit_type;

class Fruit{//抽象水果类
public:
    virtual const string& type() = 0;
};

class Apple : public  Fruit{//具体水果类
public:
    Apple() : Fruit(), m_str("Apple"){}
    const string& type() override{
        cout << m_str.data() << endl;
        return m_str;
    }
private:
    string m_str;
};

class Banana : public  Fruit{//具体水果类
public:
    Banana() : Fruit(), m_str("Banana"){}
    const string& type() override{
        cout << m_str.data() << endl;
        return m_str;
    }
private:
    string m_str;
};

class Orange : public  Fruit{//具体水果类
public:
    Orange() : Fruit(), m_str("Orange"){}
    const string& type() override{
        cout << m_str.data() << endl;
        return m_str;
    }
private:
    string m_str;
};

class juiceMaker{
public:
    Fruit* createJuice(Fruit_type type){
        switch(type){
            case apple:
                return new Apple();
            case banana:
                return new Banana();
            case orange:
                return new Orange();
            default:
                return NULL;
        }
    }
};

int main(){
    juiceMaker* f = new juiceMaker();
    Fruit* apple_j = f->createJuice(apple);
    apple_j->type();
    Fruit* banana_j = f->createJuice(banana);
    banana_j->type();

    delete apple_j;
    apple_j = NULL;
    delete banana_j;
    banana_j = NULL;
    delete f;
    f = NULL;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_32523711/article/details/109048936