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

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


/// <summary>
  /// 选答题
  /// </summary>
  [Serializable] 
  public class SelectTest
  {
    private string other;
    public string 你老婆多大
    {
      get
      {
        return this.other;
      }
      set
      {
        this.other = value;
      }
    }
  }
  /// <summary>
  /// 面试题
  /// </summary>
  public interface Itest
  {
    Itest Clone();

    string 知道设计模式吗
    {
      get;
      set;
    }
    string 设计模式有几种
    {
      get;
      set;
    }
    string 你知道那些
    {
      get;
      set;
    }
    SelectTest 附加题
    {
      get;
      set;
    }
   
  }

  /// <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;
      }
    }

    
    public Itest Clone()
    {
      SerializableHelper SerializableHelper = new 原型模式.SerializableHelper();
      string target = SerializableHelper.Serializable(this);
      return SerializableHelper.Derializable<Itest>(target); 

    }

  }


 public class SerializableHelper
  {
    public string Serializable(object target)
    {
      using (MemoryStream stream = new MemoryStream())
      {
        new BinaryFormatter().Serialize(stream, target);

        return Convert.ToBase64String(stream.ToArray());
      }
    }

    public object Derializable(string target)
    {
      byte[] targetArray = Convert.FromBase64String(target);

      using (MemoryStream stream = new MemoryStream(targetArray))
      {
        return new BinaryFormatter().Deserialize(stream);
      }
    }

    public T Derializable<T>(string target)
    {
      return (T)Derializable(target);
    }
  }

这就是对原型模式的运用。介绍完原型模式的实现代码之后,下面看下原型模式的类图,通过类图来理清原型模式实现中类之间的关系。具体类图如下:

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