Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification required - Design Patterns

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?

like image 711
Famn Avatar asked Jan 28 '26 13:01

Famn


1 Answers

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.

like image 200
Sean Patrick Floyd Avatar answered Jan 31 '26 05:01

Sean Patrick Floyd