1.)
Even though the Strategy Pattern adds complexity in terms of the number of classes in your project, the most striking benefit is that it provides a more organized way of modeling the interaction between the subclasses, interfaces, and abstract class by separating the code for executing the behaviors from the animate classes. Another benefit is that you have less duplicated code because the interface for each behavior handles all the work for each of the animates.
Joe's problem was that the relatively simple SimUDuck app needed to be extended in a way that would add a behavior to the subclasses of Duck. Joe's lack of design pattern knowledge led him to leverage inheritance to add a fly() method to Duck. The flaw with this is that every subclass that extends Duck will now be able to fly, even if it's a RubberDuck or DecoyDuck. It wouldn't be too bad to override fly() in the few subclasses that don't fly, but if Joe's manager decided that they wanted to add every variety of duck, living or otherwise, to the simulation, Joe would have to spend many a late night adding overrides to all of the sub-Ducks that can't fly. The Strategy Pattern is great for the SimUDuck project because it's easy to change and when you add methods to one of the behavior interfaces, you don't have to worry about messing up like Joe did and granting a behavior to an animate that shouldn't have it.
2)
-Sort out the methods of the superclass that vary from subclass to subclass. In the SimUDuck example, the stuff that changes is the various implementations of the fly and quack behaviors.
-Create interfaces for your behavior that hide the nitty gritty details of the implementation from the subclasses. The two interfaces in SimUDuck were FlyBehavior and QuackBehavior.
-Add classes for each variation of the stuff that changes that implement the interface, also add instance variables to each subclass that get passed to the interface and tell it which variation to perform. In SimUDuck, each Duck subclass makes calls to the behavior interface and passes it it's own behavior instance variable.
Now, when a Duck calls the performFly() method, the behavior is delegated to the FlyBehavior interface's fly() method which performs the behavior specified by the instance variable.
1 comment:
Seems you have answered all the questions in one article...But the content is right.
Your code is good, just one thing you may want to know is that most Java Programmer use two blanks instead of Tab before an indented line.
Chen
Post a Comment