使用enum枚举实现单例模式

编程

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class MyObject {

public enum MyEnumSingleton{

connectionFactory;

private Connection connection;

private MyEnumSingleton() {

try {

System.out.println("调用了MyObject构造");

String url = "jdbc:sqlserver://localhost:1079;databaseName=ghydb";

String username = "sa";

String password = "";

String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

Class.forName(driverClass);

connection = DriverManager.getConnection(url,username,password);

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

}

public Connection getConnection(){

return connection;

}

}

public static Connection getConnection(){

return MyEnumSingleton.connectionFactory.getConnection();

}

}

以上是 使用enum枚举实现单例模式 的全部内容, 来源链接: utcz.com/z/513443.html

回到顶部