这是为概念。
因此避免了import语句/ package语句。 也仅给出必要的方法。
搜索****以获取评论
由Joshua Bloch提供的有效Java
http://www.janeve.me/articles/class-...-getconnection/* ******Service interface */
public interface Connection {
... //***** Service-specific methods go here
}
/* ****** Following class implements a connection
of a particular DriverImpl */
public class ConnectionImpl implements Connection{
}
/* ******Service provider interface */
public interface Driver {
Connection getConnection() throws SqlException;
public boolean acceptsURL(String url);
}
/* ****** Following class is a Driver implementation provided by a particular DataBase vendor. The static
block is executed whenever class.forName(...) is called.*/
public class DriverImpl implements Driver {
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
private Connection getConnection()throws SQLException{
......
}
public boolean acceptsURL(String url){
......
}
}
/* ******Noninstantiable class for service registration and access */
public class DriverManager {
private DriverManager() { } // Prevents instantiation
// Stores service instances of Drivers
private static final Set<Driver> drivers = new ConcurrentHashSet<Driver>();
/**** This method is called in the static block defined
in the Driver class */
public static void registerDriver(Driver p){
drivers.put(p);
}
/*** The getConnection method which is called by our client code. This method calls getDriver() method */
public Connection getConnection(String url,....) throws SqlException{
Driver d = getDriver(url);
return d.getConnection();
}
private Driver getDriver(String url) throws SQLException{
Iterator<Driver> itr = drivers.iterator();
Driver d = null;
while(itr.hasNext()){
d = itr.next();
if ( d.acceptsURL(url) )
return d;
}
}
throw new SQLException("No driver found for " + url);
}
}
From: https://bytes.com/topic/java/insights/951463-how-drivermanager-class-implemented