一些工具类只要一个对象就够了,不需要太多。
具体如何写呢
1。懒汉式
public class Instance {
private static Instance instance=null;
private Instance()
{
}
public static Instance getInstance()
{
if(instance==null)
{
synchronized (Instance.class){
if(instance==null)
instance = new Instance();
}
}
return instance;
}
public void hello()
{
System.out.println("hello");
}
public static void main(String[] args) {
Instance.getInstance().hello();
}
}
2.饿汉式
public class Instance {
private static Instance instance=new Instance();
private Instance()
{
}
public static Instance getInstance()
{
return instance;
}
public void hello()
{
System.out.println("hello");
}
public static void main(String[] args) {
Instance.getInstance().hello();
}
}