首页 > 代码库 > 原型模式

原型模式

原型模式:对比单例模式差不多,区别原型模式复制了一个对象,相互不影响。单例模式只用一个对象

方法

namespace 原型模式
{
    /// <summary>
    /// 原型模式:对象直接克隆,相互不影响。
    /// 单例模式:对象指向一个,一个修改另外一个也修改。
    /// 
    /// </summary>
    [Serializable]
    public class StudentProperty
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public Class classs { get; set; }

        private static StudentProperty _studentProperyt;
        static StudentProperty()
        {
            Console.WriteLine("这里处理比较耗时的逻辑");
            _studentProperyt = new StudentProperty();
            _studentProperyt.classs = new Class();
        }

        /// <summary>
        /// 浅拷贝克隆:类里面有类的引用,无法克隆,还是会指向一个地址
        /// </summary>
        /// <returns></returns>
        public static StudentProperty Clone()
        {
            return (StudentProperty)_studentProperyt.MemberwiseClone();
        }

        /// <summary>
        /// 深拷贝克隆,将类直接序列号,完全克隆
        /// </summary>
        /// <returns></returns>
        public static StudentProperty SerializeClone()
        {
            string str = SerializeHelper.Serializable(_studentProperyt);
            return SerializeHelper.Derializable<StudentProperty>(str);
        }
    }


    [Serializable]
    public class Class
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

序列号帮助类

 /// <summary>
    /// 将对象序列号和反序列化
    /// </summary>
    public class SerializeHelper
    {
        public static string Serializable(object target)
        {
            using (MemoryStream stream=new MemoryStream())
            {
                new BinaryFormatter().Serialize(stream,target);
                return Convert.ToBase64String(stream.ToArray());
            }
        }

        public static T Derializable<T>(string target)
        {
            byte[] targetArray = Convert.FromBase64String(target);
            using (MemoryStream stream=new MemoryStream(targetArray))
            {
                return (T)(new BinaryFormatter().Deserialize(stream));
            }
        }
    }

主方法

    class Program
    {
        static void Main(string[] args)
        {
            StudentProperty s1= StudentProperty.Clone();
            s1.Id = 0;
            s1.Name = "张三";
            s1.Age = 12;
            s1.classs.Name = "学习1";

            StudentProperty s2 = StudentProperty.Clone();
            s2.Id = 1;
            s2.Name = "李四";
            s2.Age = 22;
            s2.classs.Name = "学习3";

            StudentProperty s3 = StudentProperty.SerializeClone();
            s3.Id = 0;
            s3.Name = "张三";
            s3.Age = 12;
            s3.classs.Name = "学习1";

            StudentProperty s4 = StudentProperty.SerializeClone();
            s4.Id = 1;
            s4.Name = "李四";
            s4.Age = 22;
            s4.classs.Name = "学习3";

            Console.ReadKey();

        }
    }

 

原型模式