博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式—原型(附带介绍浅拷贝和深拷贝)
阅读量:4339 次
发布时间:2019-06-07

本文共 1964 字,大约阅读时间需要 6 分钟。

通过拷贝创建新的对象

ColorPrototype是颜色基类(抽象类),ConcteteColorPrototype是具体的父类,他包括两个方法Clone和DeepClone,那就介绍下Clone和DeepClone的区别

Clone: 又叫浅拷贝,MemberwiseClone(),这只能拷贝一层,如果某个属性是引用类型,无法进行真正的拷贝。

DeepClone:是从对象表面到最底端,进行拷贝,是一种完全拷贝。

namespace 大话设计模式{     [Serializable]    public abstract  class ColorPrototype    {        ///         /// 克隆        ///         /// 
public abstract ColorPrototype Clone(); /// /// 深度克隆 /// ///
public abstract ColorPrototype DeepClone(); }}
public class ColorManager    {        private Hashtable colors = new Hashtable();        ///         /// 结构        ///         ///         /// 
public ColorPrototype this[string name] { get { return (ColorPrototype)colors[name]; } set { colors.Add(name, value); } } }
namespace 大话设计模式{    [Serializable]    public class ConcteteColorPrototype : ColorPrototype    {        public int red;        public int green;        public int blue;        public Student Student=new Student(){Name = "张三"};        public ConcteteColorPrototype(int red, int green, int blue)        {            this.red = red;            this.green = green;            this.blue = blue;        }        ///         /// 克隆        ///         /// 
public override ColorPrototype Clone() { return (ConcteteColorPrototype)this.MemberwiseClone(); } public override ColorPrototype DeepClone() { MemoryStream memoryStream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, this); memoryStream.Position = 0; var colorPrototype = (ColorPrototype)formatter.Deserialize(memoryStream); return colorPrototype; } } [Serializable] public class Student { public string Name { get; set; } }}

 

转载于:https://www.cnblogs.com/cainiaoguoshi/p/3454217.html

你可能感兴趣的文章
servlet filter listener区别
查看>>
DBA应该知道的一些SQL Server跟踪标记
查看>>
Leetcode 题目整理-3 Palindrome Number & Roman to Integer
查看>>
paip.复制文件 文件操作 api的设计uapi java python php 最佳实践
查看>>
Atitit.linux 内核 新特性 新功能
查看>>
Atitit 数据库view视图使用推荐规范与最佳实践与方法
查看>>
appium 环境搭建
查看>>
做开发的目的是为了什么
查看>>
JVM学习笔记(三)------内存管理和垃圾回收
查看>>
锤子辩论有感——华强北哲学之用违法创造新正义
查看>>
HashMap源码分析
查看>>
多平台密码绕过及提权工具Kon-Boot的使用与防范
查看>>
【学生信息管理系统】与后端系统接口
查看>>
WebKit介绍和总结(一)
查看>>
消息队列
查看>>
23个数据库常用查询语句
查看>>
2.c++基础函数
查看>>
Java异常处理
查看>>
WebSiteThumbnail 直接根据html生成图片
查看>>
spring security之Remember Me
查看>>