zoukankan      html  css  js  c++  java
  • 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}");
            }
        }
    

    结果:

  • 相关阅读:
    spring-boot 访问时,加与不加项目名分析
    关于文章
    随笔
    工作小结五
    《文章翻译》PCA&SVD
    工作小结四
    工作小结三
    从零开始实现SSD目标检测(pytorch)(一)
    工作小结二
    《论文翻译》 GIOU
  • 原文地址:https://www.cnblogs.com/YourDirection/p/14068995.html
Copyright © 2011-2022 走看看