Monday, 10 March 2014

Strategy Pattern

1/ Basic:

- Inheritance is a core principle of OO programing. ( IS-A Relationship)

2/ Problem:

- See the class diagram first:

- We have code duplicated across classes.
- Hard to gain knowledge of all the ducks.
- Change in super class can affect  other duck.
- Runtime behavior changes are difficult.

What about using interface ?

- Allow different classes to share similarities
- Not all classes need to have the same behaviors.



Still Problem:
- Solve part of the problem, but ...
- Absolutely destroys code reuse cause any Duck with fly() method we also need to define the fly behaviors too.
- Becomes maintain nightmare because if we change some code we need to change all.
- Does not allow runtime changes in behaviors other than flying or quacking.

Design Principle 1:

Identify the aspects of your code that vary and separate them from what stays the same.

Encapsulate What Varies:

If some aspect of code is changing
- That's sign you should pull it out and separate it.
Be separating out the parts of your code that vary
- You can extend or alter them without affecting the rest of your code.
This principle is fundamental to almost every design pattern.

All patterns let some part of the code vary independently of the other parts. It means that fewer surprises from code changes and increased flexibility in your code.

How to Design Duck class ?

Design Principle 2:

Program to an interface, not an implementation.  






Programing to an Interface with Duck:

- Rather than relying on an implementation of behavior in our duck. We're replying interface.
- FlyBehavior and QuackBehavior are now interfaces.

-> This way we are no longer locked into specific implementation.
-> A duck does not need to know detail of how they implement behavior

Conclusion:

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from client that use it.


Because it can easily change in runtime and highly re-useable : D

No comments:

Post a Comment