• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
﹏℡幸福?
博客园    首页    新随笔    联系   管理    订阅  订阅

使用枚举数据类型实现单例模式

如:
public enum  MyObject {
connectionFactory;
private Connection connection;
private MyObject(){
try {
System.out.println("调用了MyObject的构造");
String url="jdbc:oracle:thin:@118.192.22.167:1521/lbdtest01";
String username="lbdtest01";
String pwd="lbd%^test01";
String driverName="oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
connection= DriverManager.getConnection(url,username,pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection(){
return connection;
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(MyObject.connectionFactory.getConnection().hashCode());
}
}
}
class MyRun{
public static void main(String[] args) {
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
}
}
posted @ 2017-02-27 09:40  ﹏℡幸福?  阅读(488)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3