C# 设计模式(6)原型模式

原型模式

1.利用对象拷贝,快速获取对象

学生原型:

    public class StudentPrototype
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Class Class { get; set; }

        private StudentPrototype()
        {

        }

        private static StudentPrototype _studentPrototype = new StudentPrototype()
        {
            Id = 0,
            Name = "",
            Class = new Class()
            {
                Id = 0, Name = ""
            }
        };

        public static StudentPrototype GetStudentPrototype()
        {
            return (StudentPrototype) _studentPrototype.MemberwiseClone();
        }
    }

班级类:

    public class Class
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

代码调用:

    class Program
    {
        static void Main(string[] args)
        {
            StudentPrototype student1 = StudentPrototype.GetStudentPrototype();
            student1.Id = 11;
            student1.Name = "张三";
            student1.Class = new Class()
            {
                Id = 111,
                Name = "3年1班",
            };
            Console.WriteLine($"Student Id is {student1.Id },Student Name is {student1.Name},Class Id is {student1.Class.Id},Class Name is {student1.Class.Name}");

            StudentPrototype student2 = StudentPrototype.GetStudentPrototype();
            student2.Id = 22;
            student2.Name = "李四";
            student2.Class = new Class()
            {
                Id = 222,
                Name = "3年3班",
            };
            Console.WriteLine($"Student Id is {student2.Id },Student Name is {student2.Name} Class Id is {student2.Class.Id},Class Name is {student2.Class.Name}");
        }
    }

结果:

原文地址:https://www.cnblogs.com/YourDirection/p/14068995.html