Can you name and explain other common design patterns besides Singleton and Factory?
sobes.tech AI
Answer from AI
Besides Singleton and Factory, there are many common design patterns:
-
Observer: allows objects to subscribe to events of another object and receive notifications of changes. Often used for implementing event systems.
-
Decorator: dynamically adds responsibilities to objects by wrapping them in other objects with additional behavior.
-
Strategy: defines a family of algorithms, encapsulates each one, and makes them interchangeable. Allows changing the algorithm independently from clients.
-
Adapter: enables objects with incompatible interfaces to work together by converting the interface of one object into the interface expected by the client.
-
Builder: separates the construction of a complex object from its representation, allowing the creation of different representations.
Example of the Strategy pattern in Java:
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Pay " + amount + " using credit card");
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Pay " + amount + " via PayPal");
}
}
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.paymentStrategy = strategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
This pattern allows changing the payment method without modifying the cart code.