Consider a super class Animal
, inherited by multiple subclasses(Dog
/ Bird
). On their instantiation, objects have their local state & behavior:
wiki says:
The strategy pattern
- defines a family of algorithms,
- encapsulates each algorithm, and
- makes the algorithms interchangeable within that family.
If a requirement demands to add a new behavior(fly()
) in super class Animal
, then use Strategy pattern, to create new family of algorithm(CantFly
/ ItFly
) and encapsulate these algorithms in setFlyingAbility()
/tryToFly()
, to attain minimal code changes in existing class hierarchy, with below changes:
where ItFyls
and CantFly
are family of algorithms for new behavior(fly
) that are used by subclasses(Dog
/ Bird
) interchangeably, with below code changes
Association of type Composition, at crux, is helping to add new behavior in super class by minimizing code changes in super/sub class relationship, shown below,
class Animal{
....
Flys flyingType;
....
public String tryToFly(){
return flyingType.fly();
}
public void setFlyingAbility(Flys newFlyType){
flyingType = newFlyType;
}
}
Question:
To add a new behavior(fly()
) in super class(Animal
), Does Strategy pattern involves modifying every subclass(Dog
/Bird
) constructor? Can modification of subclass get avoided?