sean, , ++, .
, , . Ball, , FooBall, Foo, FooBarBall, FooBall, , Foo . , , FooBall, , Bar. , .
, , Foo Bar Ball, FooBall, Foo toFoo(). , Foo Bar .
, , Foos . - Ball, FooBall FooBarBall, . Foo Bar, -. , , Foo Bar.
#include <stdio.h>
class Ball {
public:
virtual void roll() = 0;
virtual inline ~Ball() {
printf("deleting Ball\n");
};
};
class Foo {
public:
virtual void doFoo() = 0;
virtual void complexFoo() = 0;
virtual inline ~Foo() {};
};
class Bar {
public:
virtual void doBar() = 0;
virtual void complicatedBar() = 0;
virtual inline ~Bar() {};
};
class FooBall : public Ball {
public:
virtual Foo* toFoo() = 0;
virtual inline ~FooBall() {};
};
class FooBarBall : public FooBall {
public:
virtual Bar* toBar() = 0;
virtual inline ~FooBarBall() {};
};
class FooImpl_A : public Foo {
public:
virtual void doFoo() {
printf("FooImpl_A::doFoo()\n");
};
virtual void complexFoo() {
printf("FooImpl_A::complexFoo()\n");
}
virtual inline ~FooImpl_A() {
printf("deleting FooImpl_A\n");
}
};
class FooBarImpl_A : public FooImpl_A, public Bar {
public:
virtual void doBar() {
printf("BarImpl_A::doBar()\n");
}
virtual void complicatedBar() {;
printf("BarImpl_A::complicatedBar()\n");
}
virtual inline ~FooBarImpl_A() {
printf("deleting FooBarImpl_A\n");
}
};
class FooBarBallContainer : public FooBarBall {
public:
FooBarBallContainer( Foo* realFoo, Bar* realBar, bool sameObject=true ) :
_realFoo(realFoo), _realBar(realBar), _sameObject(sameObject) {}
virtual void roll() {
_realBar->doBar();
_realFoo->complexFoo();
}
virtual Foo* toFoo() {
return _realFoo;
}
virtual Bar* toBar() {
return _realBar;
}
virtual ~FooBarBallContainer() {
delete _realFoo;
if(!_sameObject) {
delete _realBar;
}
}
private:
Foo* _realFoo;
Bar* _realBar;
bool _sameObject;
};
class FooBarBallImpl_B : public FooBarBall,
public Foo, public Bar {
public:
virtual void roll() {
complicatedBar();
doFoo();
}
virtual Foo* toFoo() {
return (Foo*) this;
}
virtual Bar* toBar() {
return (Bar*) this;
}
virtual void doFoo() {
printf("FooBarBallImpl_B::doFoo()\n");
}
virtual void complexFoo() {
printf("FooBarBallImpl_B::complexFoo()\n");
}
virtual void doBar() {
printf("FooBarBallImpl_B::doBar()\n");
}
virtual void complicatedBar() {
printf("FooBarBallImpl_B::complicatedBar()\n");
}
};
void processFooBarBall(FooBarBall *ball) {
Foo *foo = ball->toFoo();
foo->doFoo();
ball->roll();
Bar *bar = ball->toBar();
bar->complicatedBar();
}
main() {
FooBarImpl_A *fooBar = new FooBarImpl_A();
FooBarBall *container = new FooBarBallContainer(fooBar, fooBar);
printf
processFooBarBall(container);
delete container;
FooBarBallImpl_B *ball = new FooBarBallImpl_B();
processFooBarBall(ball);
container = new FooBarBallContainer(ball, ball);
processFooBarBall(container);
delete container;
}
source
share