使用枚舉數據類型實現單例模式

如:
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{@Overridepublic 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();    }}
相關文章
相關標籤/搜索