Question: java PaymentStategy Interface package StrategyPatternDemoOne; / / Strategy interface interface PaymentStrategy { void pay ( double amount ) ; } package StrategyPatternDemoOne; class PayPalStrategy implements
java
PaymentStategy Interface
package StrategyPatternDemoOne;
Strategy interface
interface PaymentStrategy
void paydouble amount;
package StrategyPatternDemoOne;
class PayPalStrategy implements PaymentStrategy
private String email;
private String password;
public PayPalStrategyString email, String password
this.email email;
this.password password;
public void paydouble amount
System.out.printlnPaying amount with PayPal.";
Perform the payment logic using PayPal credentials
package StrategyPatternDemoOne;
Concrete strategies
class CreditCardStrategy implements PaymentStrategy
private String cardNumber;
private String expiryDate;
private String cvv;
public CreditCardStrategyString cardNumber, String expiryDate, String cvv
this.cardNumber cardNumber;
this.expiryDate expiryDate;
this.cvv cvv;
public void paydouble amount
System.out.printlnPaying amount with credit card.";
Perform the payment logic using credit card details
package StrategyPatternDemoOne;
Client code
class ShoppingCart
private PaymentStrategy paymentStrategy;
public void setPaymentStrategyPaymentStrategy paymentStrategy
this.paymentStrategy paymentStrategy;
public void checkoutdouble amount
Perform the checkout process
paymentStrategy.payamount;
Driver:
package StrategyPatternDemoOne;
public class Driver
Usage
public static void mainString args
ShoppingCart cart new ShoppingCart;
Set the payment strategy dynamically
cart.setPaymentStrategynew CreditCardStrategy;
cart.checkout;
Change the payment strategy at runtime
cart.setPaymentStrategynew PayPalStrategyexample@example.com", "password";
cart.checkout;
Open imagepng
In the example above, the PaymentStrategy interface defines a contract for payment strategies, and CreditCardStrategy and PayPalStrategy are concrete implementations of the payment algorithm. The ShoppingCart class contains a reference to a PaymentStrategy object, which can be set dynamically. The client code can change the payment strategy by calling the setPaymentStrategy method.
By applying the Strategy pattern, the client code can switch between different payment strategies without modifying the core logic of the ShoppingCart class. This flexibility is especially useful when you have multiple algorithms or behaviors that need to be dynamically selected or replaced based on varying requirements.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
