假设我有一段代码:
A1 a;
A2 b;
a= function1_A();
b= function2_A();
然后我想以另一种方式做到这一点:
B1 a;
B2 b;
a= function1_B();
b= function2_B();
我做了一个策略设计模式,让两者都决定我想要的。但问题是代码与现在所有A的代表是相同的B.当然,这可能完全不同,但这超出了范围。
有没有办法设计代码以防止这种重复?
如果它只是函数,我知道我可以使用抽象超类来完成并拥有它
a=function1_SUPER();
然后每个都有正确的实现,如:
function1_SUPER(){ function1_A();}
但仍会产生大量代码。 Plus不适用于类名称,例如将A1更改为B1吗?
答案 0 :(得分:0)
我认为你必须使用模板。例如:
#include <iostream>
template <class C1, class C2> class MyClass
{
public:
C1 *function1()
{
return new C1();
};
C2 *function2()
{
return new C2();
};
};
int main()
{
MyClass<int, double> intDoubleClass;
int *a1 = intDoubleClass.function1();
double *a2 = intDoubleClass.function2();
return 0;
}
答案 1 :(得分:0)
我会在我看到的两个部分中编写问题:首先,按类型(A1,A2与B1,B2)进行分类,然后通过变量的初始化进行区分。既然你说,代码是完全相同的,但类型不是模板。所以我的第一次尝试是:
template <class X1, class X2>
struct MyStrategy {
void foo()
{
X1 a = /* create appropiate X1 */;
X2 b = /* create appropiate X2 */;
// code that is the same for both except for the types...
}
};
当然这个函数会有参数和/或返回类型,但你得到了要点。
现在到第二部分,我在评论中留下的那个:值的初始化。我会通过某种基于策略的设计来实现这一目标。第一个草图:
template <class X1, class X2>
struct X1X2Creator;
template <>
struct X1X2Creator<A1, A2> {
A1 createX1() { return function1_A(); }
A2 createX2() { return function2_A(); }
};
template <>
struct X1X2Creator<B1, B2> {
B1 createX1() { return function1_B(); }
B2 createX2() { return function2_B(); }
};
template <class X1, class X2>
struct MyStrategy : X1X2Creator<X1, X2> {
void foo()
{
X1 a = this->createX1();
X2 b = this->createX2();
// code that is the same for both except for the types...
}
};
请注意,由于它们的相关名称,您必须通过this->createX1()
调用create-functions,否则编译器应该抱怨。您也可以明确限定函数(X1X2Creator<X1, X2>::createX1()
)。
您可以根据自己的需求改进设计,例如:通过不使用继承但实例化X1X2Creator并调用函数或使它们静态。如果要使用更多不同类型的组合,请为每种类型使用一个创建策略:
template <class X1, class X2>
struct MyStrategy {
void foo()
{
X1 a = CreationPolicy<X1>::create();
X2 b = CreationPolicy<X2>::create();
// code that is the same for both except for the types...
}
};
如果您希望能够对相同类型使用不同的策略,请提供policie类作为模板参数:
template <class X1, class X2,
class X1Creator = CreationPolicy<X1>,
class X2Creator = CreationPolicy<X2>>
struct MyStrategy {
void foo()
{
X1 a = X1Creator::create();
X2 b = X2Creator::create();
// code that is the same for both except for the types...
}
};
HTH