-
The
Abstract Product
:
-
The
Concrete Product
:
-
Product A:
-
Implementation 1:
public class TableOracle implements Table {
public String toSQL() {
return "TableOracle - toSQL";
}
}
-
Implementation 2:
public class TableDerby implements Table {
public String toSQL() {
return "TableDerby - toSQL";
}
}
-
Product B:
-
Implementation 1:
public class ColumnOracle implements Column {
public String toSQL() {
return "ColumnOracle - toSQL";
}
}
-
Implementation 2:
public class ColumnDerby implements Column {
public String toSQL() {
return "ColumnDerby - toSQL";
}
}
-
The
Abstract Factory
:
public interface Schema {
public Table createTable();
public Column createColumn();
}
-
The
Concrete Factory
:
-
Implementation 1:
public class SchemaOracle implements Schema {
public Table createTable() {
return new TableOracle();
}
public Column createColumn() {
return new ColumnOracle();
}
}
-
Implementation 2:
public class SchemaDerby implements Schema {
public Table createTable() {
return new TableDerby();
}
public Column createColumn() {
return new ColumnDerby();
}
}
-
The
Factory Method
(optional):
public class FactoryMethodSchema {
public static Schema getSchema(final String type) {
if ("oracle".equalsIgnoreCase(type)) {
return new SchemaOracle();
} else if ("derby".equalsIgnoreCase(type)) {
return new SchemaDerby();
}
return null;
}
}
-
A simple class to test the
Abstract Factory
design pattern:
public class AbstractFactoryPatternTest {
public static void main(String[] args) {
// .... Example 1: Oracle Schema ....
// create the factory : Oracle
final Schema oracleSchema = FactoryMethodSchema.getSchema("oracle");
// create instances
final Table tableOracle = oracleSchema.createTable();
final Column columnOracle = oracleSchema.createColumn();
// call methods
final String s_tableOracle = tableOracle.toSQL();
final String s_columnOracle = columnOracle.toSQL();
System.out.println(s_tableOracle + " / " + s_columnOracle);
// .... Example 2: Derby Schema ....
// create the factory : Derby
final Schema derbySchema = FactoryMethodSchema.getSchema("derby");
// create instances
final Table tableDerby = derbySchema.createTable();
final Column columnDerby = derbySchema.createColumn();
// call methods
final String s_tableDerby = tableDerby.toSQL();
final String s_columnDerby = columnDerby.toSQL();
System.out.println(s_tableDerby + " / " + s_columnDerby);
}
}