In most of the design patterns concepts, it was mentioned that "Has A" is better than "Is A" means.
In the first chapter - Head First Design Patterns - "Intro to Design Patterns", section "Integrating the Duck Behaviour" (page no 15), the Duck class is having references to FlyBehavior and QuackBehavior interface types. For example, we are going to add a new behavior in feature name it XYZBehavior (just assume client has not yet decided it) for one kind of Ducks, we need to change the Duck class to have the reference to new interface. Resulting, we need to alter the class but which should not happen according to good design pattern.
Can you suggest me how can we deal with this requirement?
That problem can be solved by using Dependency Injection
(In Java usually through either Spring or Guice)
Here's a Beginner's Guide to dependency Injection
Basically, a Bird would have a behaviors property:
private Collection<Behavior> behaviors;
public void setBehaviors(Collection<Behavior> behaviors){
this.behaviors = behaviors;
}
Now in a Configuration file you would specify which Behaviors get injected into the Bird without having to change the Bird class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With