Question: Why do we need to abstract out our factory ?
Answer: Sometimes we can have a situation where we would want to club a bunch of objects together. Which may need each other to work fundamentally. e.g I have my app written to work on both Mobile and a Kiosk. But the objects created for both of these environment are totally different from each other, but as a group they need each other to work.
interface King{
String getName();
}
interface Castle{
Location getLocation();
}
interface Army{
int getSize();
}
Now there can be several kingdoms. Which will be the concrete classes of each of these interfaces.
say,
1. Marwar Kingdom has: MarwarKing, MarwarCastle and MarwarArmy concrete implementations.
2. Mughal Kingdom has: MughalKing, MughalCastle and MughalArmy concrete implementations.
3. British Kingdom has: BritishKing, BritishCastle and BritishArmy concrete implementations.
A greedy and Smart Software enginner for dynasty wants to sell his software solution to all of these dynasties, without making any change to his code. So It would make sense for him to just abstract out the Kingdom Factory.
interface Kingdom{
Army getArmy();
Castle getCastle();
King getKing();
}
class KingdomMaker{
Kingdom makeKingdom(String kingdomName){
// if else to make MarwarKingdom, Mughal or BritishKingdom according to the argument.
}
}
'Client code:
Kingdom kingdom = KingdomMaker.getKingdom("Marwar");
String kingName = kingdom.getKing.getName();
No comments:
Post a Comment