当前位置: 技术问答>java相关
请问怎么才能使一个类只生成一个实例?
来源: 互联网 发布时间:2017-03-24
本文导语: 最好举个列子,谢谢 | public class EagerSingleton { private static final EagerSingleton m_instance = new EagerSingleton(); /** * 私有的默认构造子 */ private EagerSingleton() { } /** * 静态工厂方法 */ public static E...
最好举个列子,谢谢
|
public class EagerSingleton
{
private static final EagerSingleton m_instance =
new EagerSingleton();
/**
* 私有的默认构造子
*/
private EagerSingleton() { }
/**
* 静态工厂方法
*/
public static EagerSingleton getInstance()
{
return m_instance;
}
}
{
private static final EagerSingleton m_instance =
new EagerSingleton();
/**
* 私有的默认构造子
*/
private EagerSingleton() { }
/**
* 静态工厂方法
*/
public static EagerSingleton getInstance()
{
return m_instance;
}
}
|
public class LazySingleton
{
private LazySingleton() { }
synchronized public static LazySingleton getInstance()
{
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
/**
* @label Creates
*/
private static LazySingleton m_instance = null;
}
{
private LazySingleton() { }
synchronized public static LazySingleton getInstance()
{
if (m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
/**
* @label Creates
*/
private static LazySingleton m_instance = null;
}
|
class OneInc
{
private OneInc()
{
}
static OneInc newInc()
{
return new OneInc();
}
}
{
private OneInc()
{
}
static OneInc newInc()
{
return new OneInc();
}
}
|
singleton pattern
|
public class A
{
private static A instanceA;
private A() {}
public static A getInstance()
{
if (instanceA == null)
{
instanceA = new A();
}
return instanceA;
}
}
{
private static A instanceA;
private A() {}
public static A getInstance()
{
if (instanceA == null)
{
instanceA = new A();
}
return instanceA;
}
}
|
呵呵,就是设计模式里的单态,默认的构造方法声明成私有的,搞一个方法提供这个类的静态实例
|
同意:: hymarx(偷偷给我一点爱)
单子模式结构
单子模式结构