我正在学习工厂设计模式。我无法弄清楚如何将参数传递给使用Factory模式创建的对象。
一个小傻的例子:
假设我有三个课程,Class A
和class B
以及课程Number
。 Number
是base class
。此外,类A需要三个整数并具有添加它们的功能,而类B需要两个整数并添加它们
代码段:
int main()
{
Factory *facObj = new Factory();
// Addition for Two Integers
Number * numberObjOne = facObj->createObj("AddThreeInteger");
Number * numberObjTwo = facObj->createObj("AddTwoInteger");
}
Factory.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
传递价值吗?我有意义吗?请帮助我。
答案 0 :(得分:2)
完整,可运行的示例。 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
答案 1 :(得分:1)
我不是设计模式方面的专家。所以我不确定以下建议是否仍与工厂模式兼容。
一种方法是创建不同的方法,例如CreateObjectA(int a, int b, int c)
和CreateObjectB(int a, int b)
。另一种选择是向您的方法std::vector<int>
添加createObj
。如果所有类A,B,...的整数数量不同,则可以使用向量的长度来决定要创建的对象。如果这是不可能的,你可以例如使用某种ID来告诉工厂要创建哪个对象。
答案 2 :(得分:1)
有很多方法可以做到。
一种方法是在工厂中使用单独的create方法来构造每个子类。每个create方法都会为它构造的子类获取适当的参数,并相应地将它们转发到子类的构造函数。
另一种方法是使用单独的“参数”类,以某种方式定义所创建对象的参数。它将允许指定这些参数。对于这种情况,std::vector
将适用。然后,你的create()方法必须验证传递的参数是否有效,否则抛出异常,或者沿着相同的行抛出异常。
答案 3 :(得分:1)
您可以使用模板来推广工厂类。
例如,您可以将要构建的类型发送到工厂。
这是一个可能为您的案例提供解决方案的示例:
struct Factory {
template<typename T, typename... Args>
T create(Args&&... args) {
return T{1, 2, std::forward<Args>(args)...};
}
};
它将像这样使用:
Factory factory;
auto myA = factory.create<A>(1, 2, "an additional char* parameter");
// no additional parameter works too
auto myB = factory.create<B>();
嗯,这堂课非常简单。它构造一个带有参数T
的类型Args
,加上两个int参数。但是,根据字符串的值,它不允许使用不同的类型。
顺便说一句,你应该用new
代替代码中的每个std::make_unique
,代码中有很多内存泄漏。或者,您可以创建堆栈的对象。
如果你根据发送的参数知道要构建什么类型,你可能只是重载你的函数。
这就是它的样子:
struct Factory {
A create(int a, int b, int c) {
return A{a, b, c};
}
B create(int a, int b) {
return B{a, b};
}
};
您可以像这样使用它:
Factory factory;
auto myA = factory.create(1, 2, 3);
auto myB = factory.create(1, 2);
这可能更容易实现。但请注意,您将无法拥有一个具有两个构造函数的类,也不会有两个具有相同参数的类。