一、单例模式
1、饿汉模式
//1)、定义类
class HungrySingleton
{//2)、定义静态私有字段和当前类的类型一致,并且实例化
private static HungrySingleton instance = new HungrySingleton();
//3)、定义一个私有的构造函数
private HungrySingleton() { }
//4)、定义一个静态方法,获取对象
public static HungrySingleton getInstance()
{
return instance;
}
//扩展部分
public string name;
}
static void Main(string[] args)
{
//单例:定义一个类,只能实例化出一个对象
HungrySingleton.getInstance().name="张三";
}
2、懒汉模式
class LazySingleton
{
private static LazySingleton instance;
private LazySingleton() { }
public static LazySingleton getInstance()
{
if(instance ==null)
{
instance = new LazySingleton();
}
return instance;
}
//扩展部分
public int age;
}
static void Main(string[] args)
{
//单例:定义一个类,只能实例化出一个对象
LazySingleton.getInstance().age=10;
}
二、委托
1、实例化委托delegate
delegate void delegateA1(int a);//定义委托,带参数
internal class Program
{
static void Main(string[] args)
{
delegateA1 delegateA1 = new delegateA1(A1);
A1(110);
}
static void A1(int a)
{
Console.WriteLine("A1" + a);
}
}
2、多播委托
delegate void delegateA();//定义委托
internal class Program
{
static void Main(string[] args)
{
//多播委托
delegateA delegateA = new delegateA(A0);
delegateA += A2; //委托对象可使用运算符"+"进行合并
delegateA();//A0和A2都会被执行
delegateA -= A2;//委托对象可使用运算符"-"进行移除
delegateA();//A0会被执行
}
static void A0()
{
Console.WriteLine("A0");
}
static void A2()
{
Console.WriteLine("A2");
}
}
3、匿名委托
使用:
1) //定义委托
修饰符delegate 返回值类型 委托名(参数列表);
2) //定义匿名委托
委托名 委托对象=delegate
{
//代码块
};
3) //调用匿名委托
委托对象名(参数列表);
三、事件
注意:
1、只能定义在类的里面
2、必须声明该事件的委托类型