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}");
            }
        }
    

    结果:

  • 相关阅读:
    webpack:loader编写
    架构之路:从概念开始
    AtCoder Regular Contest 114(A-C)
    12-UE4-控件类型
    10-UE4-蓝图定义简介
    11-UE4-UMG UI设计器
    UE4-目录结构简介
    UE4-字符串
    官方Spring Boot starters整理
    Java是引用传递还是值传递?
  • 原文地址:https://www.cnblogs.com/YourDirection/p/14068995.html
Copyright © 2011-2022 走看看