Apple Interview Question
Software Engineer / DevelopersTeam: Data Mining
Country: United States
this is nice insight! but how will both Tiger and Lion classes be placed ? Will they be independent clients of DrawLegsStrategy, DrawManeStrategy etc... ?
Break down the draw method into smaller pieces, Draw will use these methods to acheive full drawing. drawHead,drawBody,drawMane,drawbodycolor, have all the methods as protected.
inherite the lion class to tiger make draw virtual. override Draw method, call approrpiate primitive methods in tiger draw. if needed have extra methods in tiger class.
There is no question. You can check the programatic solution in Java at here
http:\\ideone.com\0qghO
Break down the draw method into smaller pieces, Draw will use these methods to acheive full drawing. drawHead,drawBody,drawMane,drawbodycolor, have all the methods as protected.
inherite the lion class to tiger make draw virtual. override Draw method, call approrpiate primitive methods in tiger draw. if needed have extra methods in tiger class.
Break down the draw method into smaller pieces, Draw will use these methods to acheive full drawing. drawHead,drawBody,drawMane,drawbodycolor, have all the methods as protected.
inherite the lion class to tiger make draw virtual. override Draw method, call approrpiate primitive methods in tiger draw. if needed have extra methods in tiger class.
Tempalte Design pattern can be used in this case.We can break down the draw method in several parts.Create an abstract class with the draw methos containing the various steps in the draw method.
For example
abstract class DrawAnimal
{ final void public draw()
{
drawHead();
drawBody();
drawMane();
drawStripes();
}
public void drawBody()
{
//Put code
}
public void drawHead()
{
//code
}
public void drawMane()
{
}
public void drawStripes()
{
}
}
Implement this abstract class in Lion and tiger and in case of Tiger override the methods drawmane and drawstripes.
Composition is a good idea.
The other solution i can think of is create an abstract class called CatSpecies and give all the methods there like drawHead(), drawLegs() and abstract method like draw(), also give the properties which are common.
Then derive two classes from it as Lion and Tiger and then give them individual properties and override draw().
If I guess this right, they are looking for Decorator design pattern here. Something like below.
WildAnimal -> Interface
Cat -> implements WildAnimal and draw for cat excluding mane and stripes
CatDecorator -> Decorates cat
TigerDecorator -> Concrete decorator calls cat's draw method and appends stripes
LionDecorator -> Concrete decorator calls cat's draw method and appends mane.
As per LSP (Liskov's substitution principal) inheritance is wrong choice for this problem. Strategy and composition is right choice. So break down draw into different strategy classes. DrawLegsStrategy etc. Call appropriate strategy classes from Lion and Tiger draw methods.
- raj May 22, 2012