c#设计模式==原型模式

  原型模式,这个模式还是比较容易理解的,就是在类中添加一个方法用于复制自身一个新的对象,然后返回即可,由于这次是采用c#实现的原型模式,所以只需调用this.MemberwiseClone()即可实现自身的复制,但是这个仅仅是浅复制,值类型会进行复制,但是引用类型不复制引用对象,仅仅复制引用。

  将c++和c#进行一下对比,两个最大的区别就是前者可以灵活使用指针,对内存的操作特别的方便,就比如说这个原型模式,c++只需在堆中重新分配一块内存存放自身即可。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 原型模式
{
    class Program
    {
        static void Main(string[] args)
        {
            Resume res = new Resume("小明");
            res.setpersonInfo("男", "20");
            res.setworkExprience("2010-2012", "xx公司");
            res.print();

            Resume res2 = res.Clone();
            res2.setpersonInfo("男", "22");
            res2.setworkExprience("2013-2015", "yy公司");
            res2.print();

            Resume res3 = res.Clone();
            res3.setpersonInfo("女", "24");
            res3.setworkExprience("2016-2017", "zz公司");
            res3.print();
        }
    }
}

class Resume
{
    string name;
    string sex;
    string age;
    string timeArea;
    string company;

    public Resume(string name)
    {
        this.name = name;
    }

    //设置个人信息
    public void setpersonInfo(string sex, string age)
    {
        this.sex = sex;
        this.age = age;
    }

    //设置工作经历
    public void setworkExprience(string timeArea, string company)
    {
        this.timeArea = timeArea;
        this.company = company;
    }

    //打印简历
    public void print()
    {
        Console.WriteLine("{0} {1} {2}", name, sex, age);
        Console.WriteLine("工作经历:{0} {1}", timeArea, company);
    }

    public Resume Clone()
    {
        return (Resume)this.MemberwiseClone();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值