Factory and Factory Method
Learn how to move the decision of which class to create into one place, from the simple factory to the Factory Method pattern, with a notification and a logistics example.
When you order a ride in a taxi app, you do not build the vehicle yourself. You say "bike", "auto" or "cab", and the app sends you the right one. You use the ride without caring how it was produced or which company owns it. If the app adds a new kind of ride tomorrow, you simply see one more option.
In code, the equivalent of "building the vehicle yourself" is writing new followed by a specific class name. The Factory idea moves that decision out of your everyday code and into one dedicated place. The result is that the code which uses objects no longer needs to know which exact class it received.
In this lesson you will learn two closely related ideas: the simple factory, which is a very common everyday technique, and the Factory Method pattern, which is one of the classic patterns.
01The problem: new and if/else everywhere
Suppose your application can send messages by email, SMS or push notification, depending on the user's choice. A first version often looks like this:
Notifier notifier;
if (channel.equals("EMAIL")) {
notifier = new EmailNotifier();
} else if (channel.equals("SMS")) {
notifier = new SmsNotifier();
} else if (channel.equals("PUSH")) {
notifier = new PushNotifier();
} else {
throw new IllegalArgumentException("Unknown channel: " + channel);
}
notifier.send(user, "Your order has shipped");This block works, but imagine it copied into the order service, the payment service, the reminder job and the marketing code. Now:
- The code that only wants to send a message also knows every concrete class and how to pick one.
- When you add a WhatsApp channel, you must find and edit every copy of this block.
- The client is tied to concrete classes, which goes against the Dependency Inversion Principle.
Loading the rest of the lesson…