我有一个场景,我在想我是否可以应用任何设计模式。场景是这样的:一个基类有两个派生类,在main函数中,我们需要在这两个派生类上执行相同的操作。我需要这个在c++中。
例如:
Class Base
{
virtual bool DoWeHaveToPerformOperation()=0;
virtual void PerformOperation()=0;
};
Class Derived1:public Base
{
bool DoWeHaveToPerformOperation();
void PerformOperation();
};
Class Derived2:public Base
{
bool DoWeHaveToPerformOperation();
void PerformOperation();
};
int main()
{
Derived1 d1;
if(d1.DoWeHaveToPerformOperation())
{
d1.PerformOperation();
}
Derived2 d2;
if(d2.DoWeHaveToPerformOperation())
{
d2.PerformOperation();
}
}
我不是像上面那样在main
中编写代码,而是想知道是否有一些方法可以优化代码(或者是否有可以使用的模式)。我正在考虑至少将公共代码移动到一个单独的函数中,并为这两个对象调用它,比如
CheckAndOperate(Base* b)
{
if(b->DoWeHaveToPerformOperation())
{
b->PerformOperation();
}
}
并为两个派生对象调用它。但我觉得它仍然可以优化..
int main()
{
base* b1=new derived1();
CheckAndOperate(b1);
base* b2=new derived2();
CheckAndOperate(b2);
delete b1;
delete b2;
}
有什么建议吗?
发布于 2014-04-22 02:40:00
Template Method模式通常处理这种类型的事情。
Class Base
{
public:
void PerformOperation()
{
if(DoWeHaveToPerformOperation())
{
DoPerformOperation();
}
}
protected:
virtual bool DoWeHaveToPerformOperation()=0;
virtual void DoPerformOperation() = 0;
};
Class Derived1:public Base
{
bool DoWeHaveToPerformOperation();
void DoPerformOperation();
};
Class Derived2:public Base
{
bool DoWeHaveToPerformOperation();
void DoPerformOperation();
};
int main()
{
Derived1 d1;
d1.PerformOperation();
Derived2 d2;
d2.PerformOperation();
return 0;
}
https://stackoverflow.com/questions/23203344
复制相似问题