zoukankan      html  css  js  c++  java
  • 原型模式

    定义

    通过实现对象可以复制自身,已现有自身对象为基础克隆出新对象,再在新对象上进行修改得到我们想要的实例。其本质为克隆,快速创建对象。

    类图

    代码

     1     public class ProtoSubject : ICloneable
     2     {
     3 
     4         public string Property1 { get; set; }
     5         public string Property2 { get; set; }
     6         public string Property3 { get; set; }
     7         /// <summary>
     8         /// 克隆(克隆的话,一般设为深复制)
     9         /// </summary>
    10         /// <returns></returns>
    11         public object Clone()
    12         {
    13             using (Stream s = new MemoryStream())
    14             {
    15                 BinaryFormatter formatter = new BinaryFormatter();
    16                 formatter.Serialize(s, this);
    17                 s.Seek(0, SeekOrigin.Begin);
    18                 return formatter.Deserialize(s);
    19             }
    20         }
    21         /// <summary>
    22         /// 浅复制
    23         /// </summary>
    24         /// <returns></returns>
    25         public object ShadowClone()
    26         {
    27             return this.MemberwiseClone();
    28         }
    29     }
    30 
    31     public class Client
    32     {
    33         public void TestProtoType()
    34         {
    35             ProtoSubject subject = new ProtoSubject()
    36             {
    37                 Property1 = "00001",
    38                 Property2 = "00002",
    39                 Property3 = "009",
    40             };
    41             //当现在需要一个和subject一样的对象,只是property3为“hello world”时,我们难道要重新见一个对象并重新使用初赋值语句?
    42             //而ProtoSubject已经有自身的克隆功能了,我们只需克隆一个新对象,并将需改变的属性设成我们要设置的值就可以了。
    43             ProtoSubject subject2 = (ProtoSubject)subject.Clone(); 
    44         }
    45     }

    总结

    其实这个模式非常简单,也有有些所谓的建议:类都应该实现自身的克隆方法。

    但也不是这样的,自身的克隆现在基本上不用,而是通过第三方帮助类来实现,例如:

     1    public class CloneHelper<T> where T:class
     2     {
     3         public static T Clone(T t)
     4         {
     5             using (Stream stream = new MemoryStream())
     6             {
     7                 BinaryFormatter formatter = new BinaryFormatter();
     8                 formatter.Serialize(stream, t);
     9                 stream.Seek(0, SeekOrigin.Begin);
    10                 return (T)formatter.Deserialize(stream);
    11             }
    12         }
    13     }

    我们只需调用上面的类中的静态方法就可以实现对现有类的克隆了。所以对原型模式不是很感冒...

    Top
    收藏
    关注
    评论
  • 相关阅读:
    匹配session
    Jdk1.8+Eclipse+MySql+Tomcat开发Java应用的环境搭建
    MySQL忘记密码怎么办
    MyBatis框架Maven资源
    MyBatis核心配置文件模版
    MyBatis执行过程显示SQL语句的log4j配置
    MyBatis实体类映射文件模板
    Mybatis 学习-4
    Spring Boot + Swagger
    Spring Boot + Swagger
  • 原文地址:https://www.cnblogs.com/Joy-et/p/4888476.html
Copyright © 2011-2022 走看看