What are some examples of the Strategy Pattern in Java?
The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm's behavior at runtime. For example, in a payment processing system, you could have different payment strategies like CreditCardPayment, PayPalPayment, and BitcoinPayment.
Can you show me a code example of the Strategy Pattern?
Sure! Here's a simple example:
// Strategy Interface
interface PaymentStrategy {
void pay(int amount);
}
// Concrete Strategies
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
// Context
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
In this example, the ShoppingCart
can use different payment strategies.
How do I implement this in my project?
To implement the Strategy Pattern in your project, define the strategy interface and concrete strategy classes as shown in the example. Then, in your context class (like ShoppingCart
), you can set the desired strategy at runtime based on user input or other conditions.
Get this answer and more from ChatGPT in Telegram, try it for free!
Get Started For FreePowered by advanced language models trained on billions of online words and conversations, MagicBuddy delivers friendly and helpful chat on demand.
Ask questions and get answers. Crack jokes and get laughs. Or even get writing ideas and study help. MagicBuddy's conversational intelligence allows for a truly unique and useful chat experience.
Curious? Try these prompts:
MagicBuddy is incredibly easy to use and the responses are lightning fast! 🥇
Impressive! MagicBuddy is my go-to AI assistant. It’s quick, accurate, and user-friendly.
Sending voice messages makes it easier to use in the middle of the day and the answers are super fast.
Love it! A friend of mine told me about it and it has made my life so much easier. It’s like having a helpful friend in my pocket!
I use 2 months already, simply amazing! MagicBuddy delivers answers in a snap. It’s a must-have tool for staying informed!
Game-changer! MagicBuddy’s speed and accuracy are unmatched. It’s my secret weapon for productivity
Say Hello to Your New Telegram BFF - Try MagicBuddy Free!
Get Started For Free