Sobes.tech
Junior — Middle

Can you give examples of design patterns implemented using interfaces?

sobes.tech AI

Answer from AI

Go interfaces are widely used to implement various design patterns. Here are some examples:

  1. Strategy

    • The interface defines a set of methods, and different structs implement different algorithms.
    • Example: a Sorter interface with a Sort() method, with different implementations for various sorting algorithms.
  2. Decorator

    • The interface is implemented by a base object and wrappers that add functionality.
    • Example: the Reader interface from the io package, with wrappers like bufio.Reader, gzip.Reader, etc.
  3. Factory Method

    • The interface describes a product, and factory functions return different implementations.
  4. Observer

    • An interface for subscribers that implement an update method, and an object that notifies them.

Example of a simple strategy interface and implementation:

// Strategy interface
 type PaymentMethod interface {
     Pay(amount float64) error
 }

// Implementation for credit card
 type CreditCard struct {}
 func (c CreditCard) Pay(amount float64) error {
     fmt.Println("Paying by credit card", amount)
     return nil
 }

// Implementation for PayPal
 type PayPal struct {}
 func (p PayPal) Pay(amount float64) error {
     fmt.Println("Paying via PayPal", amount)
     return nil
 }

// Usage
 func ProcessPayment(p PaymentMethod, amount float64) {
     p.Pay(amount)
 }

Thus, interfaces in Go enable flexible implementation of various patterns, ensuring loose coupling and extensibility of code.