hiwa said:
Could you elaborate on that? Small example codes attached would
greatly help understanding.
Ok...
Cars, great things for getting us around the place.
They come in many different types. At least 3 viable engine
technologies. Many, many different colours. Each manufacture make many
different models and each model typically has several different levels
within it.
So how would we model this?
How about a base class Car
Then maybe a manufactures car type, FordCar.
No hang on that doesn't work, Ford is brand, not a car, so the is-a
relation does not work here, but a Car has-a brand, hmm.. delegation.
Brand brand = car.getBrand();
Ok, so cars carry people, and typically have doors. 2, 4, 5.
So we could have 2DoorCar, 4DoorCar, 6Doorcar,... whilst it would allow
us to reuse code in the base class, the number of doors a car has is a
property of a car, its not a car itself.
So again, we have
Doors doors = new Door(4);
Car a4DoorCar = new Car(doors);
Door d = car.getDoors();
d.lock();
Ok, onto Model, lets take the BMW range.
there's the 1, 3, 5 series. So lets have
Car
|
BMWCar
|
--------------------
| | |
Series1 Series3 Series5
But hang on, they just realised a new model, the X5, do we really want
to change our class hierarchy to accommodate the new model, we'll have
to rebuild every thing and redeploy.
Or...
Model m = new Model("X5");
Car beemer = new Car(Brand, Model, doors);
beemer.getDoors().lock();
beemer.getBrand().isLuxuryBrand();
beemer.getModel().canGoOffRoad();
What I'm trying to show, is that by using delegation rather than
inheritance, we have a dynamic relationship rather than a static
relationship. Meaning the user can create all sorts of relationships at
runtime, without us having to hardcode anything.
A car has-a description (Brand, Model, Engine, Colour etc).
A car isn't aBmwSeries3TwoLitreBlackEtc.
HTH
Andrew