天天看点

Singleton设计模式介绍

Singleton就是单元素设计模式,该设计模式确保了在一个运用程序中,无论合饰地,这个类就只有一个实例可用.

适用范围.这种设计模式经常用于数据源库连接池对象等方面.因为无论你是从程序中的任何部分需要访问数据库,都是从该连接池中取出一个连接,用完后,再将连接放会连接池中.因此仅只需要一个连接池实例,该实例从第一次访问初始化,到运用程序关闭,他的生命周期才结束.

这种设计模式最大的特点是构造器设为私有,再申明一个类型为自己本身的静态私有变量myself,然后编写一个获取该类实例的静态公有方法(一般使用方法名为"getInstance()",你用其他名字也可以,但是这是一个约定俗成的规范),在这个方法中,判断,如果myself未被初始化,说明是第一次访问该对象,则调用私有构造器对myself进行初始化,然后返回myself,如果myslef已经被初始化,那直接返回myself.

下面我就以编写一个数据库连接池类来具体说明一下这种设计模式.

假设你已经在你的web容器中配制好了一个名为"jdbc/xxx"的数据源

package xxx;

import java.sql.SQLException;

import java.sql.Connection;

import javax.sql.DataSource;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import java.util.Properties;

public class ConnectionPool {

    private static String JDNI_NAME = "java:comp/env/jdbc/xxx";

    private DataSource ds;

    //申明一个类型为自己本身的变量

    [b]private static ConnectionPool mySelf;[/b]

    /**

     * 定义一个私有的构造器

     * @param ds DataSource

     */

    [b]private ConnectionPool(DataSource ds)[/b] {

        this.ds = ds;

    }

     * 获取类实例的方法

     * @return ConnectionPool

    [b]public static ConnectionPool getInstance() [/b]{

        try {

            //如果myself未被初始化过

            if (mySelf == null) {

                Context initCtx = new InitialContext();

                if (initCtx == null) {

                    throw new NamingException("error.context.init");

                }

                DataSource ds = (DataSource) initCtx.lookup(JDNI_NAME);

               //调用私有构造器对其进行实例化

                [b]mySelf = new ConnectionPool(ds);[/b]

            }

            [b]return mySelf;[/b]

        } catch (NamingException ne) {

            ne.printStackTrace();

            throw new RuntimeException("error.connectionpool.getinstance");

        }

     * 获取连接方法

     * @param autoCommit boolean

     * @return Connection

     * @throws SQLException

    public Connection getConnection(boolean autoCommit) throws SQLException {

        Connection con = ds.getConnection();

        con.setAutoCommit(autoCommit);

        return con;

}