0
0
PHPprogramming~5 mins

Strategy pattern in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the Strategy pattern?
The Strategy pattern is a design pattern that lets you choose an algorithm's behavior at runtime. It defines a family of algorithms, puts each one in a separate class, and makes their objects interchangeable.
Click to reveal answer
beginner
How does the Strategy pattern help in programming?
It helps by separating the algorithm from the code that uses it. This makes the code easier to change and extend without modifying existing code.
Click to reveal answer
intermediate
In PHP, how do you implement the Strategy pattern?
You create an interface for the strategy, then create classes that implement this interface for each algorithm. The context class holds a reference to a strategy object and delegates work to it.
Click to reveal answer
intermediate
What is the role of the Context class in the Strategy pattern?
The Context class uses a Strategy object to execute the algorithm. It does not know the details of the algorithm, only that it can call a method on the strategy.
Click to reveal answer
beginner
Give a simple real-life example of the Strategy pattern.
Choosing a payment method in an online store is like the Strategy pattern. You can pay by credit card, PayPal, or bank transfer. Each payment method is a strategy, and the store uses the chosen one to process payment.
Click to reveal answer
What does the Strategy pattern allow you to do?
ACreate multiple unrelated classes
BChange the algorithm used at runtime
CWrite code without any classes
DAvoid using interfaces
In the Strategy pattern, what does the Context class do?
AHolds a reference to a strategy and uses it
BImplements all algorithms
CDefines the interface for strategies
DCreates new strategies dynamically
Which PHP feature is commonly used to define strategies?
AInterfaces
BTraits
CAbstract classes only
DGlobal functions
Why is the Strategy pattern useful?
AIt makes code run faster
BIt forces all algorithms to be in one class
CIt removes the need for classes
DIt reduces code duplication and increases flexibility
Which of these is NOT a benefit of the Strategy pattern?
AEasier to add new algorithms
BBetter separation of concerns
CHarder to test individual algorithms
DAbility to change behavior at runtime
Explain the Strategy pattern and how it separates concerns in code.
Think about how you can swap different ways to do something without changing the main code.
You got /4 concepts.
    Describe a simple PHP example using the Strategy pattern for different sorting algorithms.
    Imagine you want to sort data but want to pick the method later.
    You got /4 concepts.