目录
一、单例模式
问题引出的怎样创建唯一变量(对象)。也就是保证一个类只有一个实例。其中单例模式又分为饿汉式和懒汉式单例。
前者是空间换时间,后者是时间换空间。单例模式包含静态的对象成员,私有的构造函数,静态的得到实例的函数。
私有构造函数确保外部不能new一个对象。GetInstance函数负责检验并实例化自己,并存储到静态成员变量中。
应用在一个类只能有一个实例时。
本质是控制实例数目。
特点:
单例类只有一个实例
必须自己创建自己的唯一实例
必须给其他对象提供这一实例
二、代码实例一
懒汉式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingLeton
{
class SingLeton
{
private static SingLeton instance;
private SingLeton()
{
}
public static SingLeton GetInstance()
{
if(instance==null)
{
instance = new SingLeton();
}
return instance;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SingLeton
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
SingLeton s1 = SingLeton.GetInstance();
SingLeton s2= SingLeton.GetInstance();
if(s1==s2)
{
Console.WriteLine("same");
}
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
}
}
}
饿汉式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingLeton
{
class SingLeton
{
private static SingLeton instance= new SingLeton();
private SingLeton()
{
}
public static SingLeton GetInstance()
{
return instance;
}
}
}
三、代码实例二--读取配置文件
考虑一个应用,读取配置文件的内存 很多项目中,都有与应用相关的配置文件,一般是自定义的,在里面定义一些应用需要的参数数据。 多采用xml格式。也有采用properties格式的。 要读取配置文件的内容,如何实现
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingLetonOne
{
class Config
{
private static Config instance;
private string A;
private string B;
private Config()
{
ReadConfig();
}
public static Config GetInstance()
{
if(instance==null)
{
instance = new Config();
}
return instance;
}
public string GetA()
{
return A;
}
public string GetB()
{
return B;
}
public void ReadConfig()
{
try
{
A = ConfigurationManager.AppSettings["pa"];
B = ConfigurationManager.AppSettings["pb"];
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SingLetonOne
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Config con = Config.GetInstance();
Console.WriteLine(con.GetA());
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
}
}
}