- Context
- Strategy
- Concrete Strategy
To separate strategies and to enable fast switching between them. Also this pattern is a good alternative to inheritance (instead of having an abstract class that is extended).
- sorting a list of objects, one strategy by date, the other by id
- simplify unit testing: e.g. switching between file and in-memory storage
You can also find this code on GitHub
Context.php
.. literalinclude:: Context.php :language: php :linenos:
Comparator.php
.. literalinclude:: Comparator.php :language: php :linenos:
DateComparator.php
.. literalinclude:: DateComparator.php :language: php :linenos:
IdComparator.php
.. literalinclude:: IdComparator.php :language: php :linenos:
Tests/StrategyTest.php
.. literalinclude:: Tests/StrategyTest.php :language: php :linenos: