1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace SingleDemo
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 Person p = Person.GetSingle("12",12);
13 //Person p2 = Person.GetSingle();
14 //Person p3 = Person.GetSingle();
15 //p.Age = 12;
16 //p2.Name = "小小明";
17 //Console.WriteLine(p3.Name+":"+p2.Age);
18 Console.ReadKey();
19 }
20 }
21 }
22
23
24 using System;
25 using System.Collections.Generic;
26 using System.Linq;
27 using System.Text;
28
29 namespace SingleDemo
30 {
31
32 //类的对象同1时刻在内存中只能有1个
33
34 class Person
35 {
36 public int Age { get; set; }
37 public string Name { get; set; }
38 private static Person p;
39
40 private Person(string name,int age)
41 {
42 this.Age = age;
43 this.Name = name;
44 }
45
46 public static Person GetSingle(string name, int age)
47 {
48 if (p == null)
49 p = new Person(name,age);
50 return p;
51 }
52 //单例模式的实现步骤
53 //1. 构造函数私有化 2.定义1个私有的静态的这个类 类型的变量
54 //3. 写1个公共的 静态的 方法 返回这个类的对象的引用
55 // 判断静态字段是否是null 如果是null 就new1个 否则直接返回
56 }
57 }