问题描述
这样的场景:
我有不同的对象执行相应的func()实现的类似操作。
func_manager()有两种解决方案,根据不同的对象调用func()
A scene like this:
I've different of objects do the similar operation as respective func() implements.
There're 2 kinds of solution for func_manager() to call func() according to different objects
解决方案1 :使用c ++中指定的虚拟函数字符。 func_manager以不同的对象点传递方式不同。
Solution 1: Use virtual function character specified in c++. func_manager works differently accroding to different object point pass in.
class Object{
virtual void func() = 0;
}
class Object_A : public Object{
void func() {};
}
class Object_B : public Object{
void func() {};
}
void func_manager(Object* a)
{
a->func();
}
解决方案2 :使用普通开关/案例。 func_manager的工作方式不同于
Solution 2: Use plain switch/case. func_manager works differently accroding to different type pass in
typedef enum _type_t
{
TYPE_A,
TYPE_B
}type_t;
void func_by_a()
{
// do as func() in Object_A
}
void func_by_b()
{
// do as func() in Object_A
}
void func_manager(type_t type)
{
switch(type){
case TYPE_A:
func_by_a();
break;
case TYPE_B:
func_by_b();
default:
break;
}
}
我的问题是2:
1.在设计图案的观点,哪一个更好?
2.在 RUNTIME EFFCIENCE 的观点,哪一个是更好? Especailly作为对象的种类增加,可能总共达到10-15,哪个人的头顶超过了另一个?我不知道switch / case如何在内部实现,只是一堆if / else?
My Question are 2:
1. at the view point of DESIGN PATTERN, which one is better?
2. at the view point of RUNTIME EFFCIENCE, which one is better? Especailly as the kinds of Object increases, may be up to 10-15 total, which one's overhead oversteps the other? I don't know how switch/case implements innerly, just a bunch of if/else?
非常感谢!
推荐答案
使用多态(解决方案1)更好。
只有一个数据点:想像一下,你有一个庞大的系统围绕两个建立,然后突然 来添加其他类型 的要求。使用解决方案一,您 添加一个派生类 ,确保在需要时实例化,并完成。使用解决方案2,您有 数千个开关
语句 在系统中涂抹,它或多或少不可能保证您找到所有必须修改新类型的地方。
Using polymorphism (Solution 1) is better.
Just one data point: Imagine you have a huge system built around either of the two and then suddenly comes the requirement to add another type. With solution one, you add one derived class, make sure it's instantiated where required, and you're done. With solution 2 you have thousands of switch
statements smeared all over the system and it is more or less impossible to guarantee you found all the places where you have to modify them for the new type.
这很难说。
我记得在Stanley Lippmann的 C ++对象模型中,他说研究表明,虚拟函数可能对于切换类型具有很小的优势。不过,我会强调引用章节,而IIRC,优势似乎不足以使决策依赖于它。
That's hard to say.
I remember a footnote in Stanley Lippmann's Inside the C++ Object Model, where he says that studies have shown that virtual functions might have a small advantage against switches over types. I would be hard-pressed, however, to cite chapter and verse, and, IIRC, the advantage didn't seem big enough to make the decision dependent on it.
这篇关于动态绑定或开关/箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!