【发布时间】:2019-03-31 03:23:06
【问题描述】:
我想创建一个行为特定的类 - 例如从函数double getValue(const int& x) const 中吐出某些值 - 基于传递给其构造函数的“类型”。现在我有两种方法:
- 存储传入的“类型”,然后每次调用
getValue中的switch语句,以确定使用哪个实现。 - 对传入的“类型”(在构造函数中)使用
switch语句来创建表示所需实现的内部对象。所以getValue本身不再需要switch。
每次调用getValue 时都会调用switch,因此方法1“似乎”效率低下。方法 2 似乎有些笨拙,因为我需要使用 <memory>,而且它还使得复制/分配我的课程变得不简单。
还有其他更简洁的方法可以解决此类问题吗?
代码示例:
#include <memory>
enum class ImplType { Simple1, Simple2 /* more cases */ };
class MyClass1
{
private:
const ImplType implType;
public:
MyClass1(const ImplType& implType) : implType(implType) { }
double getValue(const int& x) const
{
switch (implType)
{
case ImplType::Simple1: return 1; /* some implemention */
case ImplType::Simple2: return 2; /* some implemention */
}
}
};
class MyClass2
{
private:
struct Impl { virtual double getValue(const int& x) const = 0; };
struct ImplSimple1 : Impl { double getValue(const int& x) const override { return 1; /* some implemention */ } };
struct ImplSimple2 : Impl { double getValue(const int& x) const override { return 2; /* some implemention */ } };
const std::unique_ptr<Impl> impl;
public:
MyClass2(const ImplType& implType) : impl(std::move(createImplPtr(implType))) { }
static std::unique_ptr<Impl> createImplPtr(const ImplType& implType)
{
switch (implType)
{
case ImplType::Simple1: return std::make_unique<ImplSimple1>();
case ImplType::Simple2: return std::make_unique<ImplSimple2>();
}
}
double getValue(const int& x) const { return impl->getValue(x); }
};
int main()
{
MyClass1 my1(ImplType::Simple1);
MyClass2 my2(ImplType::Simple1);
return 0;
}
【问题讨论】:
-
听起来你想要一个虚拟方法(或抽象),然后在子类中以不同的方式实现它
-
MyClass2是否符合您的意思?基本上,我想避免每个实现都有多个MyClasses,并且只有一个入口点,即一个构造函数。 -
为什么要避免不同的类?
-
假设我有 100 种不同的实现,那么我希望用户通过
enum的构造函数指定所需的实现(简单直接),而不是让用户记住 100 种不同的实现类名。此外,MyImpl1 impl = MyImpl2();或MyImpl10 impl = MyImpl5();的行为不如MyImpl impl = MyImpl(Type2);或MyImpl impl = MyImpl(Type5);清晰。 -
没有必要记住 100 个不同的类名,知道枚举就足够了。看我的回答
标签: c++ class inheritance dynamic c++17