C# 设计模式 原型模式

该博客介绍了原型模式的概念,它允许通过复制原始对象来创建具有相同或相似内容的对象。示例中展示了如何在C#中实现原型模式,包括浅拷贝和深拷贝的使用,并通过一个简历类`Resume`和`WorkExperience`展示了如何创建和修改克隆对象。通过实例代码演示了如何使用原型模式创建并修改多个简历对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


原型模式就是以原始对象为模板,创建出其他相同或相似内容的同一个类型的对象,然后再此基础上,修改成最终的想要的对象。

原型模式可以使用浅拷贝,也可以使用深拷贝,根据具体的需要选择。

    class Resume: ICloneable
    {
        private string _name;
        private string _sex;
        private string _age;
        private WorkExperience _workExperience;

        public Resume(string name)
        {
            _name = name;
            _workExperience = new WorkExperience();
        }

        private Resume(WorkExperience workExperience)
        {
            _workExperience = (WorkExperience)workExperience.Clone();
        }

        public void SetPersonalInfo(string sex,string age)
        {
            _sex = sex;
            _age = age;
        }

        public void SetWorkExperience(string timeArea, string company)
        {
            _workExperience.TimeArea = timeArea;
            _workExperience.Company = company;
        }

        public void Display()
        {
            Console.WriteLine($"{_name} {_sex} {_age}");
            Console.WriteLine($"工作经历: {_workExperience.TimeArea} {_workExperience.Company}");
        }

        public object Clone()
        {
            Resume obj = new Resume(_workExperience);
            obj._name = _name;
            obj._age = _age;
            obj._sex = _sex;
            return obj;
        }
    }
    class WorkExperience: ICloneable
    {
        public string TimeArea { get; set; }
        public string Company { get; set; }

        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Resume a = new Resume("aaa");
            a.SetPersonalInfo("男", "18");
            a.SetPersonalInfo("女", "30");

            Resume b = (Resume)a.Clone();
            Resume c = (Resume)a.Clone();

            a.Display();
            b.Display();
            c.Display();

            b.SetWorkExperience("2000-2001", "however");

            a.Display();
            b.Display();
            c.Display();

            Console.WriteLine("Hello World!");
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值