Factory Method
Factory Method is the way of delegating the object creation logic to the client.
Real world example
Consider the case of a bank. It's possible for both local and foreigner to open a bank account. So the bank has to delegate the register account steps to them.
Example
BankAccount interface and implementations
interface BankAccount {
public void registerAccount();
}
class LocalAccount implements BankAccount {
public void registerAccount() {
System.out.println("Registering account for local.");
}
}
class ForeigneAccount implements BankAccount {
public void registerAccount() {
System.out.println("Registering account for foreigner.");
}
}
Bank
abstract class Bank {
abstract protected BankAccount makeBankAccount();
public void openBankAccount() {
BankAccount bankAccount = this.makeBankAccount();
bankAccount.registerAccount();
}
}
Any child can extend it and provide the required BankAccount
class LocalBankAccount extends Bank {
protected BankAccount makeBankAccount() {
return new LocalAccount();
}
}
class ForeigneBankAccount extends Bank {
protected BankAccount makeBankAccount() {
return new ForeigneAccount();
}
}
It can be used as
LocalBankAccount local = new LocalBankAccount();
local.openBankAccount(); // Output: Registering account for local
ForeigneBankAccount roreigner = new ForeigneBankAccount();
roreigner.openBankAccount(); // Output: Registering account for foreigner