Created
January 29, 2012 05:17
-
-
Save ryan-beckett/1697325 to your computer and use it in GitHub Desktop.
Demonstrates a frail implementation of the AbstractFactory pattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.lang.*; | |
class DataProviderTest | |
{ | |
public static void main (String[] args) throws java.lang.Exception | |
{ | |
String provider = "oracle"; //"derby" | |
DataProviderFactory factory = DataProviderFactory.getInstance(); | |
DataProvider dp = factory.getProvider(provider); | |
System.out.println(dp.getConnectString()); | |
} | |
} | |
interface DataProvider { | |
String getConnectString(); | |
} | |
/** | |
* You'd normally register all providers in a configuration file, which | |
* is read into a Properties instance during construction. | |
*/ | |
final class DataProviderFactory { | |
private static final DataProviderFactory INSTANCE = new DataProviderFactory(); | |
private DataProviderFactory(){} | |
public static DataProviderFactory getInstance() { | |
return INSTANCE; //better to use lazy initialization | |
} | |
public DataProvider getProvider(String provider) throws Exception { | |
String className = provider.substring(0, 1).toUpperCase() + provider.substring(1, provider.length()) + "Provider"; | |
Class<?> c = Class.forName(className); | |
return (DataProvider)c.newInstance(); | |
} | |
} | |
class OracleProvider implements DataProvider { | |
public String getConnectString() { | |
return "oracle:thin:jdbc@"; | |
} | |
} | |
class DerbyProvider implements DataProvider { | |
public String getConnectString() { | |
return "jdbc:derby@"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment