在設計模式中,有一種叫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