简单工厂笔记

UML类图入下 :

解决的问题 :

  • 解决了对象创建问题

被生产的对象接口为BaseAnimal

#ifndef __BASEANIMAL_HPP_
#define __BASEANIMAL_HPP_

#include <string>
using namespace std;

class BaseAnimal {
public:
    BaseAnimal() { }
    ~BaseAnimal() { }
    virtual string eat(string f) {
        return "";
    }
};

#endif

两个继承了BaseAnimal的子类DogCat

#ifndef __DOG_HPP_
#define __DOG_HPP_
#include "BaseAnimal.hpp"
class Dog : public BaseAnimal {
public:
    Dog(/* args */) { }
    ~Dog() { }
    virtual string eat(string f) {
        return "dog eat " + f;
    }
};
#endif

#ifndef __CAT_HPP_
#define __CAT_HPP_
#include "BaseAnimal.hpp"

class Cat : public BaseAnimal {
public:
    Cat(/* args */) { }
    ~Cat() { }

    virtual string eat(string f) {
        return "cat eat " + f;
    }
};
#endif

最主要的是工厂类AnimalFactory

#ifndef __ANIMALFATORY_HPP_
#define __ANIMALFATORY_HPP_
#include "BaseAnimal.hpp"
#include "Cat.hpp "
#include "Dog.hpp "

class AnimalFactroy {
public:
    enum TYPE_ANIMAL { TYPE_CAT, TYPE_DOG };

    AnimalFactroy() { }
    ~AnimalFactroy() { }

    static BaseAnimal* createAnimal(TYPE_ANIMAL type) {
        // 根据不同的入参 type生成不同的对象
        // 好处是main里不用知道有Cat类和Dog类,实现了解耦
        if (TYPE_CAT == type) { return new Cat(); }
        if (TYPE_DOG == type) { return new Dog(); }
    }
};

最后是调用方main函数里

signed main() {
    // 这里调用方并不知道有Dog和Cat的存在,但是却可以new出不同的动物
    BaseAnimal* animal = AnimalFactroy::createAnimal(AnimalFactroy::TYPE_DOG);
    show(animal->eat(" shit "));

    animal = AnimalFactroy::createAnimal(AnimalFactroy::TYPE_CAT);
    show(animal->eat( "fish "));
    return 0;
}
posted @ 2021-06-12 21:16  马角的逆袭  阅读(39)  评论(0)    收藏  举报