A design pattern that selects the algorithm’s behavior dynamically. Basically,this is a behavioral design pattern. It follows the runtime instruction to choose the algorithm. So it is more flexible.
How to implement the strategy design pattern?
It includes the three major components.
Strategy Interface: It is the basic for all
implementation.
Concrete Strategies: It implements the interface with
specific functionality.
Context class: this is thee one which allows the
strategy to choose at runtime.
A shopping Application is developed here.
Strategy interface: PayBillStrategy
CreditCardPay ,PayPalPay : concrete strategy
Billpay() is used to pay the bill. It is overridden for two
strategy.
Context class: Shopping Cart
setPayBillStrategy() : Select the strategy at runtime.
Checkout() : used to send cart to bill payment.
Shop App : It is the class with main function. It creates
the objects and call the context class member functions.
#Java Program to implement the strategy design pattern
interface PayBillStrategy {
void billpay(int
amount);
}
class CreditCardPay implements PayBillStrategy {
private String
cardNo;
public
CreditCardPay(String cardNo) {
this.cardNo =
cardNo;
}
public void
billpay(int amt) {
System.out.println("Paid " + amt + " using Credit Card
Payment: " + cardNo);
}
}
private String
emailid;
public
PayPalPay(String emailid) {
this.emailid =
emailid;
}
@Override
public void
billpay(int amt) {
System.out.println("Paid " + amt + " using PayPal
payment: " + emailid);
}
}
class ShoppingCart {
private
PayBillStrategy paybillStrategy;
// Setting the
strategy at runtime
public void
setPayBillStrategy(PayBillStrategy paybillStrategy) {
this.paybillStrategy = paybillStrategy;
}
public void
checkout(int amt) {
paybillStrategy.billpay(amt);
}
}
public class ShopApp {
public static void
main(String[] args) {
ShoppingCart
cart1 = new ShoppingCart();
System.out.println("Shopping Application");
System.out.println("Your Billing deatails:");
// Using
Credit Card Pay bill strategy
cart1.setPayBillStrategy(new
CreditCardPay("9876-5432-0129-8765"));
cart1.checkout(230);
cart1.setPayBillStrategy(new
PayPalPay("customer@rajeevas.com"));
cart1.checkout(180);
}
}
While executing this program, you get the below output.
C:\raji\blog>javac ShopApp.java
C:\raji\blog>java ShopApp
Shopping Application
Your Billing deatails:
Paid 230 using Credit Card: 9876-5432-0129-8765
Paid 180 using PayPal: customer@rajeevas.com
This strategy is flexible and maintainable. Thus the way of
strategy design pattern in java was implemented using a shopping application.