個人資料
  • 博客訪問:
正文

J2EE Design Pattern - Factory Pattern & Example

(2008-01-09 21:26:15) 下一個

The Factory Pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.

Intent
Encapsulate the creation of an object.

Motivation
The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns.

Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized build-up and tear-down concerns of the object.

Example:

DBConnectionFactory.java
import java.sql.*;
import java.util.*;

/**
 * Title: DBConnectionFactory
 * Description: Serves as an abstract class for implementing database connection factory
 */

public abstract class DBConnectionFactory
{
  protected Hashtable mProperties = new Hashtable();

  public DBConnectionFactory(Hashtable aProperties)
  {
    mProperties = aProperties;
  }

  public abstract Connection getConnection(String aConnectionName) throws java.sql.SQLException;

}

DataSourceConnectionFactory.java
import java.sql.Connection;
import java.util.*;
import javax.naming.*;
import javax.sql.DataSource;
public class DataSourceConnectionFactory extends DBConnectionFactory
{

  public DataSourceConnectionFactory(Hashtable aProperties)
  {
     super(aProperties);
  }
  public Connection getConnection(String aJndiConnectionName) throws java.sql.SQLException
  {
    Connection con = null;
    try
    {
      InitialContext ic = new InitialContext();
      DataSource ds = (DataSource) ic.lookup(aJndiConnectionName);
      con = ds.getConnection();
    }
    catch(Exception err)
    {
      err.printStackTrace();
    }
    return con;

  }

Database connection pool and datasource definition in config.xml
<JDBCConnectionPool CapacityIncrement="1"DriverName="oracle.jdbc.driver.OracleDriver" InitialCapacity="0"MaxCapacity="25" Name="rtmsRefPool"PasswordEncrypted="{3DES}6SADFJKLJDAF2dsLKSJDFAJ=="Properties="user=REF_UPDATE" Targets="snsserver"TestConnectionsOnReserve="true" TestTableName="DUAL" URL="jdbc:oracle:thin:@(DESCRIPTION=(LOAD_BALANCE=on)(FAILOVER=on)(enable=broken)(ADDRESS_LIST=(ADDRESS =(PROTOCOL=TCP)(HOST=USHD04vip)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=IAMST2)(SERVER=DEDICATED)(FAILOVER_MODE=(TYPE=SELECT)( METHOD=BASIC)(RETRIES=20)(DELAY=2))))"/>

<JDBCDataSource JNDIName="rtmsRefPool" Name="rtmsRefPool"PoolName="rtmsRefPool" Targets="snsserver"/>

[ 打印 ]
閱讀 ()評論 (1)
評論
目前還沒有任何評論
登錄後才可評論.