INTRODUCTION
We have got some idea about the Factory Method Design Pattern, but what is Abstract Factory Design Pattern? It is nothing but the FACTORY of FACTORIES. A factory which provides the another factory based on the input provided.
USECASE
Get the state’s (within India) language based on the North India and South India states.
IMPLEMENTATION
Lets create a State Interface.
public interface State {
String getLanguage();
}
|
Create States Tamilnadu, Andra, Gujarath, and Delhi which implements the State Interface.
public class Tamilnadu implements State {
@Override
public String getLanguage() {
return "tamil";
}
}
|
Create an IndiaFactory interface which is implemented by SouthIndiaFactory and NorthIndiaFactory.
public interface IndiaFactory {
State getState(String stateName);
}
|
Now create SouthIndiaFactory which has the south India's states Tamilnadu & Andra and create NorthIndiaFactory which has Delhi & Gujarat.
public class SouthIndiaFactory extends IndiaFactory {
@Override
State getState(String stateName) {
if (stateName.equalsIgnoreCase("tamilnadu")) {
return new Tamilnadu();
} else if (stateName.equalsIgnoreCase("andra")) {
return new Andra();
}
return null;
}
}
|
Now time to test the Abstract Factory pattern.
public class AbstractFactoryPatternTest {
public static void main(String[] args) {
// South India
IndiaFactory southIndiaFactory = IndiaFactoryProducer.getDivision("south");
State tamilnadu = southIndiaFactory.getState("tamilnadu");
System.out.println("Tamilnadu's language: " + tamilnadu.getLanguage());
State andra = southIndiaFactory.getState("andra");
System.out.println("Andra's language: " + andra.getLanguage());
// North India
IndiaFactory northIndiaFactory = IndiaFactoryProducer.getDivision("north");
State gujarath = northIndiaFactory.getState("gujarath");
System.out.println("Gujarath's language: " + gujarath.getLanguage());
State delhi = northIndiaFactory.getState("delhi");
System.out.println("Delhi's language: " + delhi.getLanguage());
}
}
|
OUTPUT
Tamilnadu's language: tamil
Andra's language: telugu
Gujarath's language: gujarathi
Delhi's language: hindi
|
Complete Source Code
Hope this example clarifies the Abstract Factory Design Pattern. Please share your thoughts in the comment box.
Hope this example clarifies the Abstract Factory Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!
No comments :
Post a Comment