samedi 23 septembre 2017

Is strategy pattern used to add state(data member)?

Consider a super class(can be abstract) Animal, inherited by multiple subclasses(Dog / Bird). On their instantiation provide objects having their local state & behavior:

enter image description here


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 algorithm(or behavior)(not state) in super class Animal, then use Strategy pattern, with below changes:

enter image description here

where ItFyls and CantFly are algorithms encapsulating the new behavior(fly) that are used by subclasses(Dog / Bird) interchangeably, with below code changes

enter image description here

Association of type Composition, is helping to add/change behavior in super class by minimizing side effects in super/sub class relationship.

class Animal{
    ....
    Flys flyinType;
    ....
}


Is strategy pattern suppose to be used to only add new behavior(or algorithm) in super class? but not state(data)

Aucun commentaire:

Enregistrer un commentaire