using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*单例模式确保一个类只有一个实例,并提供一个全局访问点*/
namespace 单例模式
{
public class Singleton
{
//懒汉模式,只有在需要的时候才实例化
/*饿汉模式,加载时即实例化
* private static Singleton uniqueinstance = new Singleton();
*/
//为了运行效率采用懒汉模式
private static Singleton uniqueinstance;
//为了实现多线程下的线程安全,使用互斥锁
private static readonly object locker = new object();
private Singleton()
{ }
public static Singleton creatinstance()
{
//使用双重检测同步延迟加载去创建单例的做法是一个非常优秀的做法,
//其不但保证了单例,而且切实提高了程序运行效率
if (uniqueinstance == null)
{
lock (locker)
{
if (uniqueinstance == null)
{
uniqueinstance = new Singleton();
}
}
}
return uniqueinstance;
}
public void write()
{
Console.WriteLine("hello");
}
}
class Program
{
static void Main(string[] args)
{
Singleton a = Singleton.creatinstance();
a.write();
//创建b的时候因为uniqueinstance不为空,所以跳过了实例creatinstance,返回了和a一样的creatinstance
Singleton b = Singleton.creatinstance();
b.write();
Console.ReadKey();
}
}
}
单例模式是最简单最常用的设计模式,主要用来读取保存系统的配置文件,在没有系统的学习设计模式前,我大都采用静态类来完成,学习比较,单例模式和静态类,总结各路大神们的观点,单例模式主要有一下几个优点:
1,可以被延迟初始化,初始化比较灵活;2,单例模式可以有多态,而全静态的类不能支持多态;3,单例可以继承类,实现接口
初学设计模式,只能照猫画虎,如果有大神能有更通俗易懂的解释还请不吝赐教,多谢!
参考:1,https://www.cnblogs.com/zhtao_tony/p/3956047.html
2,https://blog.csdn.net/fuzhongmin05/article/details/71001857
3,http://www.cnblogs.com/zhili/p/SingletonPatterm.html