方法一(懒汉式):
package singleton;
public class Singleton {
static Singleton singleton = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
}
package singleton;
public class SingletonTest {
/**
* @param args
*/
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
}
}
方法二(饿汉式):
package singleton;
public class Singleton {
static Singleton singleton = null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
package singleton;
public class SingletonTest {
/**
* @param args
*/
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
}
}