Factory Method Pattern
[tr] Türkçe Oku 2023-06-11
Once upon a time, there was a magical kingdom, and its name was “Factory Method”. This kingdom was a place that controlled the creation of objects. The wisest ruler of the kingdom believed that the creation of objects had its own special ways, and this was part of his rule.
The ruler had a princess, and her name was “Creator”. Creator used her magical powers every day to create a new object. However, Creator did not always create the same type of object. Some days she would create a “ProductA”, other days she would create a “ProductB”. Each product was created in a slightly different way, so Creator had to create each one individually.
This story is implemented in the C# language as follows:
public abstract class Creator
{
public abstract IProduct FactoryMethod();
}
public class ConcreteCreatorA : Creator
{
public override IProduct FactoryMethod()
{
return new ConcreteProductA();
}
}
public class ConcreteCreatorB : Creator
{
public override IProduct FactoryMethod()
{
return new ConcreteProductB();
}
}
The same story in Java:
public abstract class Creator {
public abstract Product factoryMethod();
}
public class ConcreteCreatorA extends Creator {
@Override
public Product factoryMethod() {
return new ConcreteProductA();
}
}
public class ConcreteCreatorB extends Creator {
@Override
public Product factoryMethod() {
return new ConcreteProductB();
}
}
In Python:
from abc import ABC, abstractmethod
class Creator(ABC):
@abstractmethod
def factory_method(self):
pass
class ConcreteCreatorA(Creator):
def factory_method(self):
return ConcreteProductA()
class ConcreteCreatorB(Creator):
def factory_method(self):
return ConcreteProductB()
In Go:
type Creator interface {
FactoryMethod() Product
}
type ConcreteCreatorA struct{}
func (c ConcreteCreatorA) FactoryMethod() Product {
return &ConcreteProductA{}
}
type ConcreteCreatorB struct{}
func (c ConcreteCreatorB) FactoryMethod() Product {
return &ConcreteProductB{}
}
And in Rust:
pub trait Creator {
fn factory_method(&self) -> Box<dyn Product>;
}
pub struct ConcreteCreatorA;
impl Creator for ConcreteCreatorA {
fn factory_method(&self) -> Box<dyn Product> {
Box::new(ConcreteProductA)
}
}
pub struct ConcreteCreatorB;
impl Creator for ConcreteCreatorB {
fn factory_method(&self) -> Box<dyn Product> {
Box::new(ConcreteProductB)
}
}
And so, the inhabitants of the Factory Method kingdom saw how the Creator created objects. Each Creator has the ability to create a specific type of product, which makes the code neater, understandable, and flexible.
For each new type of product, we can create a new Creator, and this will expand the creative abilities of the Creator. This story demonstrates how the Factory Method design pattern works and how it can be used. This pattern controls the creation of objects and makes the code easier to maintain and extend.