A
alessio211734
I am reading a design pattern book.
the example is a class duck that a method fly
class duck
{
virtual void fly(){......}
void display();
}
class FakeDuck: public duck()
{
void fly(){ override to nothing...}
}
if I have a FakeDuck class it's need to override the fly method to
nothing because a FakeDuck can't fly.
And so on for every subclass of duck that have no fly feature.
book propose the pattern strategy and to extern the fly behavior as a
external class
class FlyBehavior
{
virtual void fly()=0;
}
class NoFly: public FlyBehavior
{
virtual void fly(){ printf("can't fly")};
and the class duck became
class duck
{
FlyBehavior * bhv;
void performFly(){ bhv->fly(); }
}
I have doubts about the design proposed because book says
encapsulating the algorithms in a class hierarchy and make them
interchangeable.
But ok if I need the private data about duck class to implement the
fly method of NoFly class how can do it??
What's the best solutions?
Thanks in advance.
Ale.
the example is a class duck that a method fly
class duck
{
virtual void fly(){......}
void display();
}
class FakeDuck: public duck()
{
void fly(){ override to nothing...}
}
if I have a FakeDuck class it's need to override the fly method to
nothing because a FakeDuck can't fly.
And so on for every subclass of duck that have no fly feature.
book propose the pattern strategy and to extern the fly behavior as a
external class
class FlyBehavior
{
virtual void fly()=0;
}
class NoFly: public FlyBehavior
{
virtual void fly(){ printf("can't fly")};
and the class duck became
class duck
{
FlyBehavior * bhv;
void performFly(){ bhv->fly(); }
}
I have doubts about the design proposed because book says
encapsulating the algorithms in a class hierarchy and make them
interchangeable.
But ok if I need the private data about duck class to implement the
fly method of NoFly class how can do it??
What's the best solutions?
Thanks in advance.
Ale.