Java
Usage examples: The Strategy pattern is very common in Java code. It’s often used in various frameworks to provide users a way to change the behavior of a class without extending it.
Java 8 brought the support of lambda functions, which can serve as simpler alternatives to the Strategy pattern.
Here some examples of Strategy in core Java libraries:
java.util.Comparator#compare()called fromCollections#sort().javax.servlet.http.HttpServlet:service()method, plus all of thedoXXX()methods that acceptHttpServletRequestandHttpServletResponseobjects as arguments.
Identification: Strategy pattern can be recognized by a method that lets a nested object do the actual work, as well as a setter that allows replacing that object with a different one.
Payment method in an e-commerce app
In this example, the Strategy pattern is used to implement the various payment methods in an e-commerce application. After selecting a product to purchase, a customer picks a payment method: either Paypal or credit card.
Concrete strategies not only perform the actual payment but also alter the behavior of the checkout form, providing appropriate fields to record payment details.
strategies
strategies/PayStrategy.java: Common interface of payment methods
package refactoring_guru.strategy.example.strategies;
/**
* Common interface for all strategies.
*/
public interface PayStrategy {
boolean pay(int paymentAmount);
void collectPaymentDetails();
}strategies/PayByPayPal.java: Payment via PayPal
strategies/PayByCreditCard.java: Payment via credit card
strategies/CreditCard.java: A credit card class
order
order/Order.java: Order class
Demo.java: Client code
OutputDemo.txt: Execution result
Last updated