Factory Method

noun

say it: “FAK-tuh-ree METH-ud” /ˈfæktəri ˈmɛθəd/

A design pattern where a base class leaves the choice of which object to create to its subclasses.

What is Factory Method?

Factory Method — A design pattern where a base class does its work with an object it gets from a method it doesn't fill in itself; each subclass overrides that method to create the right kind. The base class never names a concrete class.

abstract class Notifier
{
    protected abstract IMessage CreateMessage(string text); // the factory method
    public void Send(string text) => CreateMessage(text).Deliver();
}
class EmailNotifier : Notifier
{
    protected override IMessage CreateMessage(string text) => new EmailMessage(text);
}

In a sentence

  • “With the Factory Method pattern, EmailNotifier and SmsNotifier each create their own kind of message.”

Level: Freelancer · More OOP terms at this level

Updated