I am trying to understand the strategy pattern, here is an example, we have a Customer
that has a method GetDiscount
, this method is written as follows
GetDiscount
If (Condition1)
Return 10%
else (Condition2)
Return 20%
Now I have refactored the code using the strategy pattern so it becomes
GetDiscount
Invoke the attached strategy
And we create two strategy class 10%Strategy
and 20%Strategy
to encapsulate the behavior of the discount
And for the client code to use the customer class it becomes
c = new Customer
if(condition1)
c.attach(10%Strategy)
else (condition2)
c.attach(20%Strategy)
c.GetDiscount
So as you can see we have moved the conditionals from inside Customer
class into the client code, not only this, but this conditional branching itself is considered a business logic and we let it to leak into client code that might be a presentation controller for example.
Am I missing something?
Aucun commentaire:
Enregistrer un commentaire