Junior
Tell me about the Factory design pattern.
sobes.tech AI
Answer from AI
Factory Method — a creational pattern that defines an interface for creating objects but allows subclasses to decide which class to instantiate.
Main components:
- Product: An interface or abstract class that defines the type of objects created by the factory method.
- Concrete Product: A specific implementation of the Product.
- Creator: A class that declares the factory method, which returns an object of type Product. It may provide a default implementation or leave it abstract.
- Concrete Creator: A subclass of Creator that overrides the factory method to create specific Concrete Products.
Advantages:
- Flexibility: Allows adding new product types without changing client code that uses the factory.
- Loose coupling: Separates object creation code from its usage.
- Ease of extension: Adding a new product requires creating a new Concrete Product and a new Concrete Creator.
Example implementation in Go:
// Product
type Shape interface {
Draw() string
}
// Concrete Product
type Circle struct{}
func (c *Circle) Draw() string {
return "Drawing a Circle"
}
// Concrete Product
type Square struct{}
func (s *Square) Draw() string {
return "Drawing a Square"
}
// Creator
type ShapeFactory interface {
CreateShape() Shape
}
// Concrete Creator
type CircleFactory struct{}
func (cf *CircleFactory) CreateShape() Shape {
return &Circle{}
}
// Concrete Creator
type SquareFactory struct{}
func (sf *SquareFactory) CreateShape() Shape {
return &Square{}
}
// Usage
func main() {
circleFactory := &CircleFactory{}
circle := circleFactory.CreateShape()
fmt.Println(circle.Draw()) // Output: Drawing a Circle
squareFactory := &SquareFactory{}
square := squareFactory.CreateShape()
fmt.Println(square.Draw()) // Output: Drawing a Square
}