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

    结果:

  • 相关阅读:
    CentOS 7 虚拟机的安装
    2 MySQL rpm
    01-在实体类上加了lombok的@Data注解
    02-myBatisPlus的wrapper接口的使用
    2 MySQL rpm 安装 --下载
    1-MySQL介绍
    MySQL的不归路
    电脑型号4 1500 内存大 机械大硬盘
    电脑型号3 1200 大硬盘
    电脑概览 2 1200 固态SSD
  • 原文地址:https://www.cnblogs.com/YourDirection/p/14068995.html
Copyright © 2011-2022 走看看