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:
-
Strategy
- The interface defines a set of methods, and different structs implement different algorithms.
- Example: a
Sorterinterface with aSort()method, with different implementations for various sorting algorithms.
-
Decorator
- The interface is implemented by a base object and wrappers that add functionality.
- Example: the
Readerinterface from theiopackage, with wrappers likebufio.Reader,gzip.Reader, etc.
-
Factory Method
- The interface describes a product, and factory functions return different implementations.
-
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.