Sobes.tech
Junior — Middle

Can you name some design patterns besides Singleton?

sobes.tech AI

Answer from AI

In addition to Singleton, there are many other design patterns that help solve common development problems:

  • Factory Method — creating objects through a factory method, allowing delegation of creation to subclasses.
  • Observer — a pattern for notifying multiple objects about changes in the state of another object.
  • Decorator — dynamically adding new responsibilities to an object without changing its structure.
  • Strategy — defining a family of algorithms that can be interchanged at runtime.
  • Adapter — transforming the interface of one class into another interface expected by the client.

Example of using the Strategy pattern:

interface PaymentStrategy {
    void pay(int amount);
}

class CreditCardPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Payment of " + amount + " with a credit card");
    }
}

class PayPalPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Payment of " + amount + " via PayPal");
    }
}

class ShoppingCart {
    private PaymentStrategy paymentStrategy;

    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.paymentStrategy = strategy;
    }

    public void checkout(int amount) {
        paymentStrategy.pay(amount);
    }
}
Can you name some design patterns besides Singleton… - sobes.tech