单实例模式
无聊,学习,学习,搞了个单实例模式
单一实例,就是在整个应该 访问的,是这一个内存实例,对外不暴露构造函数,通过静态函数取对象
/**
* @author Administrator
*
*/
public class SingletonPatternPerson {
private static SingletonPatternPerson singletonPattern=null;
/**定义private 为的时不让外界 实例化,只能自己实例化,不能怎么单一呢
*
*/
private SingletonPatternPerson()
{
}
/**
* 获取单一实列
* @return
*/
public static SingletonPatternPerson getInstance()
{
if(singletonPattern==null) //为空,实例化
singletonPattern=new SingletonPatternPerson();
return singletonPattern;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SingletonPatternPerson sing=SingletonPatternPerson.getInstance();
SingletonPatternPerson singO=SingletonPatternPerson.getInstance();
if(sing==singO)
System.out.println("我们相等!!");
}
* @author Administrator
*
*/
public class SingletonPatternPerson {
private static SingletonPatternPerson singletonPattern=null;
/**定义private 为的时不让外界 实例化,只能自己实例化,不能怎么单一呢
*
*/
private SingletonPatternPerson()
{
}
/**
* 获取单一实列
* @return
*/
public static SingletonPatternPerson getInstance()
{
if(singletonPattern==null) //为空,实例化
singletonPattern=new SingletonPatternPerson();
return singletonPattern;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SingletonPatternPerson sing=SingletonPatternPerson.getInstance();
SingletonPatternPerson singO=SingletonPatternPerson.getInstance();
if(sing==singO)
System.out.println("我们相等!!");
}
}
//上面代码严格来说,有点问题,下面对于多线程,启动的时候,有可能同时访问这个方法,因此会出现两个,解决很容易哦,在private static SingletonPatternPerson singletonPattern=new SingletonPatternPerson ();就初史化
public static SingletonPatternPerson getInstance()
{
if(singletonPattern==null) //为空,实例化
singletonPattern=new SingletonPatternPerson();
return singletonPattern;
}
单实例,还是蛮简单,用的到的地方,还是蛮多
{
if(singletonPattern==null) //为空,实例化
singletonPattern=new SingletonPatternPerson();
return singletonPattern;
}
单实例,还是蛮简单,用的到的地方,还是蛮多