Can you list and describe the main methods of implementing design patterns in code?
sobes.tech AI
Answer from AI
Main methods of implementing design patterns in Java code:
-
Inheritance and polymorphism — often patterns use abstract classes or interfaces to define a common contract, and concrete implementations inherit and override methods.
-
Composition — instead of inheritance, objects include other objects that implement the desired behavior (for example, the Strategy pattern).
-
Use of interfaces and abstract classes — to define common methods and ensure flexibility.
-
Factory methods and object creation patterns — to manage object creation through special methods or classes (for example, Factory, Builder).
-
Delegation — passing calls to other objects to divide responsibilities.
Example of implementing the Strategy pattern:
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Payment by credit card: " + amount);
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Payment via PayPal: " + amount);
}
}
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.paymentStrategy = strategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
This approach allows changing behavior at runtime without modifying client code.