---
title: "Singleton单例模式"
author: "crackit"
date: "2011-05-12T22:28:23Z"
tags: []
categories: ["企业架构"]
slug: "singleton"
draft: false
lastmod: "2011-05-12T22:28:23Z"
id: 1041846
url: "https://crackit.iteye.com/blog/1041846"
---

## Singleton单例模式 -- java模式

1. 单例模式

 ConnectionPool.java

```
package com.mark.util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * Singleton get database connection 
 *
 */
public class ConnectionPool {
	private static ConnectionPool connectionPool = null;
	private static Connection connection = null;
	
	/*
	 * create ConnectionPool
	 */
	private ConnectionPool() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * get ConnectionPool
	 */
	public static ConnectionPool getInstance() {
		if(connectionPool == null) {
			connectionPool = new ConnectionPool();
		}
		return connectionPool;
	}
	
	/*
	 * get connection
	 */
	public Connection getConnection() {
		if(connection != null) {
			return connection;
		}
		return null;
	}
}
```