谁能告诉我这件事有什么作用?如果有人能举例说明是否有帮助。
public class ConnectionManager{
private static ConnectionManager instance = null;
.....}
以下是完整的代码:
package com.gollahalli.main;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionManager
{
private static ConnectionManager instance = null;
private final String USERNAME = "root";
private final String PASSWORD = "root";
private final String H_CONN_STRING = "jdbc:hsqldb:data/explorecalifornia";
private final String M_CONN_STRING = "jdbc:mysql://localhost/explorecalifornia";
private DBType dbType = DBType.MYSQL;
private Connection conn = null;
private ConnectionManager() { }
public static ConnectionManager getInstance() {
if (instance == null) {
instance = new ConnectionManager();
}
return instance;
}
public void setDBType(DBType dbType) {
this.dbType = dbType;
}
private boolean openConnection() {
try {
switch (dbType) {
case MYSQL:
conn = DriverManager.getConnection(M_CONN_STRING, USERNAME, PASSWORD);
return true;
case HSQLDB:
conn = DriverManager.getConnection(H_CONN_STRING, USERNAME, PASSWORD);
return true;
default:
return false;
}
}
catch (SQLException e) {
System.err.println(e);
return false;
}
}
public Connection getConnection() {
if (conn == null) {
if (openConnection()) {
System.out.println("Connection opened");
return conn;
} else {
return null;
}
}
return conn;
}
public void close() {
System.out.println("Closing connection");
try {
conn.close();
conn = null;
} catch (Exception e) { }
}
}
答案 0 :(得分:2)
它用于确保只能创建一个类的一个实例。
public class MySingletonClass {
private static MySingletonClass instance;
public synchronized static MySingletonClass getInstance() {
if (instance == null) {
instance = new MySingletonClass(); // "lazy" initialization
}
return instance;
}
/**
* private constructor can be called only inside of MySingleton class, but not from outside.
*/
private MySingletonClass() {
// your code here
}
}
因此,要在代码中获取此类的实例,开发人员不使用构造函数。
开发人员使用静态方法getInstance()
。
MySingletonClass mySingleton = MySingletonClass.getInstance();
请小心单身。许多新手开发人员滥用单例并将其用作全局变量。不要这样做:)
<强>更新强>
我在synchronized
方法中添加了getInstance()
以使其线程安全。
答案 1 :(得分:1)
它只是声明一个名为instance
的字段,其类型为ConnectionManager
并将其初始化为null
(这是多余的,因为无论如何这都是默认值)。
很可能这个类是一个单例类(只允许一个实例),由instance
字段声明和类的名称来判断。
答案 2 :(得分:1)
它被称为Singleton pattern。
当您只需要一个类的一个对象(单例)时使用。它只构造一次,然后你可以通过getInstance()来访问它。
天真的实施
public class SingletonDemo {
//Holds the singleton
private static SingletonDemo instance = null;
//Overrides default constructor, not to instantiate another one.
//Only getInstance will construct
private SingletonDemo() { }
//Only this method can construct a singleton, always call this one
public static SingletonDemo getInstance() {
if (instance == null) { //No singleton yet, create one
instance = new SingletonDemo();
}
//return the singleton (created this time or not)
return instance;
}
}