在设计模式中,有一种叫Singleton模式的,用它能够实现一次只运行一个实例。就是说在程序运行期间,某个类只能有一个实例在运行。这种模式用途比较普遍,会常常用到,下面是Singleton模式的两种实现方法:
一、饿汉式
web
publicclassEagerSingleton
{
privatestaticreadonlyEagerSingleton instance =newEagerSingleton();
privateEagerSingleton(){}
publicstaticEagerSingleton GetInstance()
{
returninstance;
}
}设计模式
publicclassLazySingleton
{
privatestaticLazySingleton instance =null;
privateLazySingleton(){}
publicstaticLazySingleton GetInstance()
{
if(instance ==null)
{
instance =newLazySingleton();
}
returninstance;
}
}ide
两种方式的比较:饿汉式在类加载时就被实例化,懒汉式类被加载时不会被实例化,而是在第一次引用时才实例化。这两种方法没有太大的差异,用哪一种均可以。post