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值类型时的坑的示例

  • 相关阅读:
    生成R文件
    android开发问题汇总
    雅虎股票接口
    Ext4.1 , #Ext4.2
    MSSQL手工注入 报错注入方法
    MSSQL 数据库复制脚本
    Go VS Code 调式常见问题处理
    Win10 VS2012 无法注册IIS4.0 解决方案
    VirtualBox 局域网独立主机设置
    如何用.reg文件操作注册表
  • 原文地址:https://www.cnblogs.com/caiyangcc/p/13047246.html
Copyright © 2011-2022 走看看