设计模式之外观模式(facade)

为子系统中的一组接口提供一个一致的界面。

Java 外观模式示例

Facade一个典型应用就是数据库JDBC的应用,

  • Connection
  • PreparedStatement
  • ResultSet
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestJDBC
{

  public static Connection getConnect() throws ClassNotFoundException, SQLException
  {
    // 通过的反射的方式,导入数据库连接驱动
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbcurl";
    Connection conn = DriverManager.getConnection(url, "root", "root");
    System.out.println("connect mysql is success ? " + !conn.isClosed());
    return conn;
  }

  public static void testSelect() throws ClassNotFoundException, SQLException
	{
		Connection conn = getConnect();

		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			String sql = "select * from pangugle_user";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery(sql);
			while(rs.next())
			{
				long userid = rs.getLong("user_id");
				String username = rs.getString("user_name");
				String password = rs.getString("user_password");
				System.out.println(" userid = " + userid + ",  username = " + username + ", password = " + password);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally
		{
			// 一定要关闭资源(当然我们还有一种技术,叫做连接池技术,就不在需要我们来关闭了)
			ps.close();
			conn.close();
			rs.close();
		}
	}

}