C#编程中使用设计模式中的原型模式的实例讲解

2019-12-26 17:41:16王振洲

 

复制克隆:复印机


 /// <summary>
  /// 继承Itest接口
  /// </summary>
  public class Test : Itest
  {
    private string one;
    private string two;
    private string three;
    private SelectTest other=new SelectTest();
    public string 知道设计模式吗
    {
      get
      {
        return this.one;
      }
      set
      {
        this.one = value;
      }
    }
    public string 设计模式有几种
    {
      get
      {
        return this.two;
      }
      set
      {
        this.two = value;
      }
    }
    public string 你知道那些
    {
      get
      {
        return this.three;
      }
      set
      {
        this.three = value;
      }
    }
    public SelectTest 附加题
    {
      get
      {
        return this.other;
      }
      set
      {
        this.other = value;
      }
    }
    #region IColorDemo 成员

    public Itest Clone()
    {
      //克隆当前类
      return (Itest)this.MemberwiseClone();
    }
    #endregion
  }

客户端,发卷做题


 static void Main()
    {
      //印刷试卷
      Itest test = new Test();
      //复制样本试卷
      Itest test1 = test.Clone();
      
      //考生1
      test.设计模式有几种 = "23";
      test.附加题.你老婆多大 = "18";

      //考生2
      test1.设计模式有几种 = "24";
      test1.附加题.你老婆多大 = "20";

      //显示考生答卷内容
      Console.WriteLine("test设计模式有几种:" + test.设计模式有几种);  //23
      Console.WriteLine("test附加题.你老婆多大:" + test.附加题.你老婆多大);  //20
      Console.WriteLine("test1设计模式有几种:" + test1.设计模式有几种);  //24
      Console.WriteLine("test1附加题.你老婆多大:" + test1.附加题.你老婆多大); //20

      Console.ReadKey();
    }

注意:这里两个人答得不一样,为什么附加题中,老婆年龄都为20?

这里涉及到深拷贝,浅拷贝问题,值类型是放在栈上的,拷贝之后,会自会在站上重新add一个,而class属于引用类型,拷贝之后,栈上重新分配啦一个指针,可指针却指向同一个位置的资源。浅拷贝,只拷贝值类型,深拷贝,引用类型也拷贝复制。

解决方案:


 public Itest Clone()
    {
      //克隆当前类
      Itest itst= (Itest)this.MemberwiseClone();
      SelectTest st = new SelectTest();
      st.你老婆多大 = this.other.你老婆多大;
      itst.附加题 = st;
      return itst;

    } 

使用序列化解决