简单工厂模式

正如其名简单工厂模式的思想很简单,就是把复杂代码封装起来便于日后重复调用。我们会使用new MyClass()来创建一个对象。但这种方法十分原始,无法胜任许多情形。

在JDBC中我们需要获得一个Connection来连接数据库。数据库可能是MySQL、Oracle、SQLServer等等。Java提供了java.sql.DriverManager来帮助你连接各种数据库。客户端只需要调用DriverManager.getConnection(String url, String user, String password)方法就可以。

getConnection的代码大概是这样的:

//这段代码是将JavaSE8源码简化、修改后的代码
//修改前的代码还是挺复杂的
//可以看到简单工厂模式可以根据不同的参数(这里是指url)创建并返回不同类型的对象
Connection getConnection(String url) throws SQLException {
    SQLException reason = null;

    //遍历目前支持的数据库,如果url字符串语法正确就返回对应的Connection
    for(DriverInfo aDriver : registeredDrivers) {
        try {
            Connection con = aDriver.driver.connect(url);
            if (con != null) {
                return (con);
            }
        } catch (SQLException ex) {
            if (reason == null) {
                reason = ex;//只有第一次失败会记录该异常
            }
        }
    }

    if (reason != null) {
        throw reason;
    }

    throw new SQLException("No suitable driver found for "+ url, "08001");
}

客户端代码:

Connection connection = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/dbname?user=root&password=123456");
/*do something*/
connection.close();

简单工厂模式的思路主要是:

  • 将创建对象的复杂过程封装起来。
  • 根据参数不同创建不同的对象。

简单工厂模式也有很多局限性,我们之后还将接触到抽象工厂模式和工厂方法模式。

posted @ 2016-01-09 00:46  FJNU陈东  阅读(257)  评论(0编辑  收藏  举报