饿汉式
线程安全
public class Computer {
private Computer(){}
private static Computer computer=new Computer();
public static Computer getInstance(){
return computer;
}
}
懒汉式
线程不安全
public class PC {
private PC(){}
private static PC pc;
public static PC getPc(){
if (pc==null){
pc=new PC();
}
return pc;
}
}
静态内部类
线程安全
public class Server {
private Server(){}
public static Server getInstance(){
return Inner.server;
}
public static class Inner{
public static final Server server=new Server();
}
}
双重锁模式
线程安全
public class PCs {
private PCs(){}
private volatile static PCs pCs;
public static PCs getInstance(){
if (pCs==null){
synchronized (PCs.class){
if (pCs==null){
pCs=new PCs();
}
}
}
return pCs;
}
}