zoukankan      html  css  js  c++  java
  • 学习笔录——大话设计模式——原型模式

    学习笔录——设计模式

    原型模式(Prototype)

    简介

    原型模式就是从一个对象在创建另一个可定制的对象,而不需要知道任何创建的细节。

    代码示例

     
        public class WorkDeep : ICloneable
        {
            public string WorkDate { get; set; }
    
            public string Company { get; set; }
    
            public object Clone()
            {
                return (object)this.MemberwiseClone();
            }
        }
    
        public class ResumeDeep : ICloneable
        {
            public string Name { get; set; }
            public int Age { get; set; }
    
            public WorkDeep Work { get; set; }
    
            private ResumeDeep(WorkDeep work)
            {
                this.Work = (WorkDeep)work.Clone();
            }
    
            public ResumeDeep(string name, int age)
            {
                this.Name = name;
                this.Age= age;
                this.Work = new WorkDeep();
            }
            
            public void SetWork(string company, string workDate)
            {
                this.Work.WorkDate = workDate;
                this.Work.Company = company;
            }
    
            public void Display()
            {
                System.Console.WriteLine(this.Name + this.Age);
                System.Console.WriteLine($"{this.Work.Company} {this.Work.Company}");
            }
    
            public object Clone()
            {
                ResumeDeep resume = new ResumeDeep(this.Work);
                resume.Name = this.Name;
                resume.Age = this.Age;
                return resume;
            }
        }
    
        static void Main(string[] args)
        {
            // Resume resume = new Resume("hmy");
            // resume.SetPersonInfo(21);
            // resume.SetWorkExperience("2020","YH");
    
            // Resume resume1 = (Resume)resume.Clone();
            // resume1.SetWorkExperience("2019", string.Empty);
    
            ResumeDeep resume3 = new ResumeDeep("hmy", 21);
            resume3.SetWork("2020","YH");
    
            ResumeDeep resume4 = (ResumeDeep)resume3.Clone();
            resume4.SetWork("2019", string.Empty);
    
            resume3.Display();
            resume4.Display();
    
            Console.Read();
        }
    
    

    个人理解,不足之处还请指教。

    需要注意值类型和引用类型,在进行复制时的区别,浅复制只会复制值类型,引用类型只会复制引用,比如我在EFCore值类型时的坑的示例

    EFCore值类型时的坑的示例

  • 相关阅读:
    web 学习资源整理
    CodeSmith 学习资料收集
    常用 T_SQL 语句
    SQL Server 2000查询分析器自定义查询快捷键
    插入标识列 identity_insert
    c# 上传FTP文件
    (.Net 3.5Sp1)WebForm使用System.Web.Routing
    SPQuery.ViewAttributes
    ChatterBot之linux下安装mongodb 02
    linux端口开放指定端口的两种方法
  • 原文地址:https://www.cnblogs.com/caiyangcc/p/13047246.html
Copyright © 2011-2022 走看看