构造函数单例模式

 

单例模式只能实例化一次,重复实例化时属性不变

例:某某岗位只有一个人,无论如何重复调用,人员属性不变 

 public class privately   //单例模式
        {
            private static privately pri;  //定义
public int age; public string name; public static privately Pri //判断是否已经存在,如果否,实力化,若已被实例化,则禁止实例 { get { if (pri == null) { pri = new privately(); } return pri; } } private privately() //私有构造,不能在外界定义(因为用的是private私有属性,所以外面调不到,所以不能实力化) { } public void Me() { Console.WriteLine("My name is " + name +@",I'm "+age+" years old"); }
            copy_file.privately man= copy_file.privately.Pri;  //调用私有函数

            man.age = 23; 
            man.name = "tt";
            man.Me();
            copy_file.privately man_1 = copy_file.privately.Pri; 
            man_1.Me();  //无论如何更改都无法改变私有函数的实例

 

posted @ 2018-09-20 22:31  邢韬  阅读(1555)  评论(0编辑  收藏  举报