OOP C++: Which pattern: 2 classes with the partly same methods
Problem description:
I need to implement 2 classes like following:
class A1 {
common_method1();
common_method2();
foo1();
};
class A2 {
common_method1();
common_method2();
foo2();
};
foo1() and foo2() has different logic.
foo1() and foo2() may have different args and return values. common methods are the same OR have similar logic.Target: To implement factory that is able to generate A1 or A2 objects.
After call to factory::create() use foo1() or foo2() method respectively to the type of the object generated.Question How better to implement 开发者_如何学Gosuch logic in C++ C++/CLI?
THANKS!
I think this is definitely a standard inheritance pattern. Create a base class Parent
, which implements common_method1
and common_method2
. Create classes A1
and A2
which inherit from Parent
.
If you need to do some special casing in one of the common_method1
or common_method2
methods in either A1
or A2
, make the methods virtual
in Parent
.
Implement foo1
and foo2
in respectively A1
and A2
.
EDIT: If I understand you correctly, you want to create a factory that returns a Parent
type reference (abstract class). If you want to always foo1
on A1
objects, and foo2
on A2
objects, simply create a virtual method bar
in the Parent
interface, which, overriden in A1
, will simply call foo1
, and, overriden in A2
, will simply call foo2
.
I would create a base class that implements the common functionality. Then use inheritance to create your final classes.
Your factory could return a pointer to the base class, which could include methods to determine the type. Or you could type cast it if needed.
Not knowing much else about your example, I think you'll want to create a master class that contains the common methods and then inherit those to a couple of base classes. Then you can use polymorphism to call either foo1() or foo2(). This site on polymorphism may help you since it's using the classic circle/square draw() example.
You might want to have a heirarchy as such:
#include <iostream>
struct A_Base {
// You can put your other common method here
virtual void common_method();
virtual ~A_Base();
}
struct A1 : A_Base {
void foo1();
};
struct A2 : A_Base {
void foo2();
};
struct Factory {
// I'm just using an int for the condition,
// but you can use anything
A_Base *CreateA(int i) {
if( i == 1 ) return new A1;
if( i == 2 ) return new A2;
}
};
int main()
{
Factory f;
// Create an object
A_Base *pb = f.CreateA(1);
A1 *pa1;
A2 *pa2;
// Run a common method
pb->common_method();
// Check the runtime type
// (not really necessary, but you might need it)
if( pa1 = dynamic_cast<A1*>(pb) ) {
pa1->foo1(); // Run the unique method
} else if ( pa2 = dynamic_cast<A2*>(pb) ) {
pa2->foo2(); // Or run the other unique method
}
// Delete the pointer
delete pb;
return 0;
}
Yeah I'm using RTTI here near the end; not really good practice but you might need to know how to do that base->derived conversion
精彩评论