The following design pattern is categorized as a creational pattern.
An abstract factory is used to provide an interface for creating families of related objects, without specifying concrete classes and can be used to hide platform specific classes.
interface Tool {
void use();
}
interface ToolFactory {
Tool create();
}
class GardenTool implements Tool {
@Override
public void use() {
// Do something...
}
}
class GardenToolFactory implements ToolFactory {
@Override
public Tool create() {
// Maybe additional logic to setup...
return new GardenTool();
}
}
class FarmTool implements Tool {
@Override
public void use() {
// Do something...
}
}
class FarmToolFactory implements ToolFactory {
@Override
public Tool create() {
// Maybe additional logic to setup...
return new FarmTool();
}
}
Then a supplier/producer of some sort would be used which would be passed information that would allow it to give back the correct type of factory implementation:
public final class FactorySupplier {
// The supported types it can give you...
public enum Type {
FARM, GARDEN
};
private FactorySupplier() throws IllegalAccessException {
throw new IllegalAccessException("Cannot be instantiated");
}
public static ToolFactory getFactory(Type type) {
ToolFactory factory = null;
switch (type) {
case FARM:
factory = new FarmToolFactory();
break;
case GARDEN:
factory = new GardenToolFactory();
break;
} // Could potentially add a default case to handle someone passing in null
return factory;
}
}