c++ - 工厂模式中的传值

标签 c++ design-patterns factory-pattern

我正在学习工厂设计模式。我无法弄清楚如何将参数传递给使用工厂模式创建的对象。

一个愚蠢的小例子:

假设我有三个类,Class Aclass B 以及 Class NumberNumber基类。此外,A 类需要三个整数并具有将它们相加的功能,而 B 类需要两个整数并将它们相加

代码片段:

int main()
{

    Factory *facObj = new Factory();
    // Addition for Two Integers
    Number * numberObjOne = facObj->createObj("AddThreeInteger");
    Number * numberObjTwo = facObj->createObj("AddTwoInteger");
}

工厂.cpp

Number * Factory::createObj(string str)
{
    if (str == "AddThreeInteger")
    {
        return new A(1,2,3);
    }
    else if (str == "AddTwoInteger")
    {
        return new B(1,2);
    }
    else            
        return NULL;
}

问题:现在无论我做什么我都只能添加硬编码的数字。如何从我的客户端代码或 main() 传递这些整数值。这是一个愚蠢的例子,我是编程新手。请在这里帮助我。我怎么能不对值进行硬编码并获得结果呢。我可以通过某种方式传递 facObj->createObj 处的值吗?我说得通吗?请帮助我。

最佳答案

完整的、可运行的示例。 c++11 或更高版本。

注意 unique_ptr 的使用。不要使用原始指针。

#include <iostream>
#include <memory>
#include <stdexcept>
#include <exception>
#include <utility>

template<class T, class...Args>
struct creatable_from {
    template<class X, class...Ys>
    static auto test(int) -> decltype(X(std::declval<Ys>()...), void(), std::true_type());

    template<class X, class...Ys>
    static auto test(...) -> decltype(std::false_type());

    static constexpr auto value = decltype(test<T, Args...>(0))::value;

};

struct Operation {
    virtual ~Operation() = default;

    virtual int operator()() const = 0;
};

struct Add : Operation
{
    Add(int x, int y)
    : x(x), y(y)
    {}

    int operator()() const override {
        return x + y;
    }

    int x, y;
};

struct Sub : Operation
{
    Sub(int x, int y)
    : x(x), y(y)
    {}

    int operator()() const override {
        return x - y;
    }

    int x, y;
};

struct AddSub : Operation
{
    AddSub(int x, int y, int z)
    : x(x), y(y), z(z)
    {}

    int operator()() const override {
        return x + y - z;
    }

    int x, y, z;
};

struct Factory
{
    template<class...Args>
    std::unique_ptr<Operation> create(const std::string& type, Args&&...args)
    {
        if (type == "Add") {
            return do_create<Add>(std::forward<Args>(args)...);
        }
        if (type == "Sub") {
            return do_create<Sub>(std::forward<Args>(args)...);
        }
        if (type == "AddSub") {
            return do_create<AddSub>(std::forward<Args>(args)...);
        }

        // default - return a null pointer, but would probably be better to
        // throw a logic_error
        return {};
    }

private:
    template<class T, class...Args>
    static auto do_create(Args&&...args)
    -> std::enable_if_t< creatable_from<T, Args...>::value, std::unique_ptr<T> >
    {
        return std::make_unique<T>(std::forward<Args>(args)...);
    }

    template<class T, class...Args>
    static auto do_create(Args&&...args)
    -> std::enable_if_t< not creatable_from<T, Args...>::value, std::unique_ptr<T> >
    {
        throw std::invalid_argument("wrong number of arguments");
    }

};

int main()
{

    auto facObj = Factory();
    auto t1 = facObj.create("Add", 2, 3);
    auto t2 = facObj.create("Sub", 3, 2);
    auto t3 = facObj.create("AddSub", 2, 3, 4);

    std::cout << (*t1)() << std::endl;
    std::cout << (*t2)() << std::endl;
    std::cout << (*t3)() << std::endl;
}

预期输出:

5
1
1

关于c++ - 工厂模式中的传值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374368/

相关文章:

c++ - 错误 : variable or field ‘myfunction’ declared void

c++ - C++中的数据库程序问题

没有参数名称的C++构造函数

c++ - 我的谓词函数有什么问题?

design-patterns - Kafka 架构很多分区还是很多主题?

c# - 分配通用异常 <TException> 一条消息

java - 有没有什么方法可以设计我的 Java 代码,使这两个对象不引用自身?

design-patterns - 工厂模式中的参数化工厂 - 是否存在其他方式?

design-patterns - 将依赖注入(inject)与工厂模式混合在一起好吗?

c# - 在抽象工厂模式中使用 IoC?