Abstract Factory comes under creational design pattern.
It provides one more level of abstraction than Factory method.
Just as factory methods connects parallel class implementations,
Abstract Factory connects parallel factories. It returns one of
the available factories based on some condition.
Behaviour & Advantages
Instantiates one of the available factories based on some condition.
Connects families of related classes or toolkits.
Client doesn't need to know the factory implementation class.
Abstract factory may auto detect which factory to instantiate or
it can also be parameterized just like factory method.
The detection logic is implementation dependent.
In this example we have created a DBConnectionFactory which instantiates
either OracleConnectionFactory or MySQLConnectionFactory based on
some system property. After getting a specific factory, performing other operations
is similar irrespective of the implementation.
/**
* Get Connection from OracleConnectionFactory
*/
System.setProperty("DB_CONNECTION_FACTORY",
"com.bethecoder.tutorials.dp.abstract_factory.oracle.OracleConnectionFactory");
IConnectionFactory factory = DBConnectionFactory.getConnectionFactory();
IConnection connection = factory.getConnection();
System.out.println("Obtained connection for DB Vendor : " + connection.getVendorName());
/**
* Get Connection from MySQLConnectionFactory
*/
System.setProperty("DB_CONNECTION_FACTORY",
"com.bethecoder.tutorials.dp.abstract_factory.mysql.MySQLConnectionFactory");
factory = DBConnectionFactory.getConnectionFactory();
connection = factory.getConnection();
System.out.println("Obtained connection for DB Vendor : " + connection.getVendorName());
}
}
It gives the following output,
Obtained connection for DB Vendor : Oracle 11g
Obtained connection for DB Vendor : MySQL 6.0