`
VincentZheng
  • 浏览: 51554 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Proto Type

    博客分类:
  • Java
 
阅读更多
package com.DesignPatterns;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * The prototype is typically used to clone an object, i.e. to make a copy of an
 * object. When an object is complicated or time consuming to be created , you
 * may take prototype pattern to make such object cloneable. Assume the Complex
 * class is a complicated, you need to implement Cloneable interface and
 * override the clone method(protected Object clone()).
 */
public class ProtoType {

	public static final int SHALLOW_COPY = 0;
	public static final int CLONEABLE_COPY = 1;
	public static final int SERIALIZABLE_COPY = 2;

	public static void printDatainfo(int copyType, Complex complex)
			throws CloneNotSupportedException, IOException,
			ClassNotFoundException {

		complex.id = 123;
		complex.city = "New York";
		complex.populations = new int[]{1, 2, 3, 4, 5};

		if (copyType == SHALLOW_COPY || copyType == CLONEABLE_COPY) {
			complex.clonedQuoted = new ClonedQuoted(456, "London");
		}
		if (copyType == SHALLOW_COPY || copyType == SERIALIZABLE_COPY) {
			complex.serializedQuoted = new SerializedQuoted(789, "Paris");
		}

		Complex copyedComplex = null;
		if (copyType == SHALLOW_COPY) {
			complex.isShallowCopy = true;
			copyedComplex = (Complex) complex.clone();
		} else if (copyType == CLONEABLE_COPY) {
			complex.isShallowCopy = false;
			copyedComplex = (Complex) complex.clone();
		} else if (copyType == SERIALIZABLE_COPY) {
			copyedComplex = (Complex) deepCopy(complex);
		}

		System.out.println("change String or int value:");
		complex.id = 321;
		complex.city = "纽约";
		System.out.println(complex);
		System.out.println(copyedComplex);
		System.out.println();

		System.out.println("change Array value:");
		complex.populations[0] = 5;
		System.out.println(complex);
		System.out.println(copyedComplex);
		System.out.println();

		if (copyType == SHALLOW_COPY || copyType == CLONEABLE_COPY) {
			System.out.println("change Cloneable Object value:");
			complex.clonedQuoted.id = 654;
			complex.clonedQuoted.city = "伦敦";
			System.out.println(complex);
			System.out.println(copyedComplex);
			System.out.println();
		}

		if (copyType == SHALLOW_COPY || copyType == SERIALIZABLE_COPY) {
			System.out.println("change Serializable Object value:");
			complex.serializedQuoted.id = 987;
			complex.serializedQuoted.city = "巴黎";
			System.out.println(complex);
			System.out.println(copyedComplex);
		}
	}

	public static Object deepCopy(Object obj) throws IOException,
			ClassNotFoundException {

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(obj);

		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bis);

		return ois.readObject();
	}

	public static void main(String[] args) throws CloneNotSupportedException,
			IOException, ClassNotFoundException {

		/**
		 * A shallow copy of the original object can only store the basic
		 * variable just as int, boolean, etc. If the cloned object changed the
		 * value of quoted object just as Array, list, etc, the original object
		 * will be changed accordingly, vice versa.
		 */
		Complex complex = new Complex();
		System.out.println("Shallow copy:");
		printDatainfo(SHALLOW_COPY, complex);

		/**
		 * To avoid such side effect, you may use a deep copy instead of a
		 * shallow copy. There are 2 ways to implement it.
		 */
		complex = new Complex();
		System.out.println();
		System.out
				.println("**********************************************************************************");
		System.out.println();
		System.out.println("Deep copy(implement by cloneable):");
		printDatainfo(CLONEABLE_COPY, complex);

		complex = new Complex();
		System.out.println();
		System.out
				.println("**********************************************************************************");
		System.out.println();
		System.out.println("Deep copy(implement by Serializable):");
		printDatainfo(SERIALIZABLE_COPY, complex);
	}
}

class Complex implements Cloneable, Serializable {

	static final long serialVersionUID = 1L;
	int id;
	String city;
	int[] populations;
	ClonedQuoted clonedQuoted;
	SerializedQuoted serializedQuoted;
	boolean isShallowCopy;

	@Override
	protected Object clone() throws CloneNotSupportedException {

		Complex complex = (Complex) super.clone();
		
		if (!isShallowCopy) {

			complex = (Complex) super.clone();
			complex.clonedQuoted = ((ClonedQuoted) complex.clonedQuoted.clone());
			complex.populations = complex.populations.clone();
		}
		return complex;
	}

	@Override
	public String toString() {

		String str = "Complex:{ {id=" + id + ", city="
				+ city + ", populations=";

		for (int i : populations) {
			str += i + ",";
		}
		str = str.substring(0, str.length() - 1) + "}*****";

		if (clonedQuoted != null) {
			str += "Cloned: {id=" + clonedQuoted.id + ", city="
					+ clonedQuoted.city + "}*****";
		}
		if (serializedQuoted != null) {
			str += "Serialized: {id=" + serializedQuoted.id
					+ ", city=" + serializedQuoted.city + "} }";
		}

		return str;
	}
}

class ClonedQuoted implements Cloneable {

	int id;
	String city;

	public ClonedQuoted() {
	}

	public ClonedQuoted(int id, String city) {
		this.id = id;
		this.city = city;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

class SerializedQuoted implements Serializable {

	static final long serialVersionUID = 2L;
	int id;
	String city;

	public SerializedQuoted() {
	}

	public SerializedQuoted(int id, String city) {
		this.id = id;
		this.city = city;
	}
}
分享到:
评论

相关推荐

    腾讯TNN的示例model

    腾讯TNN的示例model 下载了一天 才下载成功。分享出来方便大家 最近更新版本: darrenyao87 committed on 16 Sep 16, 2020

    基于Asp.Net设计的学生成绩信息管理系统(源码+论文+文献综述+外文翻译).zip

    so that it can not only be applied in on eeducational in stitution.In choosing the developing methods,we combine the life sycle approach and the proto type-based approach,approach infourmain steps:...

    proto2graphql:将协议缓冲区(proto3)中的架构定义转换为GraphQL

    proto2graphql 将协议缓冲区(proto3)中的架构定义转换为GraphQL。 可用于帮助生成到gRPC后端服务的GraphQL API网关。...}GraphQL type SearchRequest { query : String pageNumber : Int resultPerPage : Int}

    net-proto:一个用于获取网络协议信息的Ruby接口

    描述net-proto软件包提供了一种获取协议信息的方法。... get_protocol ( 'icmp' ) # => 1# Using type specific methodsNet :: Proto . getprotobynumber ( 6 ) # => 'tcp'Net :: Proto . getprotob

    深入浅析JavaScript中prototype和proto的关系

    __proto__:每个对象都有一个名为__proto__的内部隐藏属性,指向于它所对应的原型对象(chrome、firefox中名称为__proto__,并且可以被访问到)。原型链正是基于__proto__才得以形成 (note:不是基于函数对象的属性...

    make-proto:从yaml为erlang制作proto

    pt-num:协议号pt-type:服务器| s | 客户| c pt-marco:宏名字pt-alias:协议号字符串(别名)pt注释:协议注释,插入解释方法前pt-content:协议内容key0:val0 key1:val1 keyx:valx 方法 gen_pt_marco2num.scm ...

    protoc-3.4.0-win32

    include\google\protobuf\type.proto include\google\protobuf\descriptor.proto include\google\protobuf\api.proto include\google\protobuf\empty.proto include\google\protobuf\compiler include\google\...

    javascript 中__proto__和prototype详解

    __proto__是内部原型,prototype是构造器原型(构造器其实就是函数) 构造器的原型(prototype)是一个对象 那什么是构造器呢? 要想创建一个对象,首先要有一个对象构造器,就像php里面一样,要想创建一个对象,...

    js prototype和__proto__的关系是什么

    即:对象具有属性__proto__,每个对象都会在其内部初始化一个属性,就是__proto__,当我们访问一个对象的属性 时,如果这个对象内部不存在这个属性,那么他就会去__proto__里找这个属性,这个__proto__又会有自己的_...

    starlarkproto:在Starlark中支持protobuffers

    type = "GREETING" # Enums can be assigned by String, Int or proto.Enum print ( m ) # Message(body = Hello, world!, type = GREETING, ...) greeting = test . Message . Type . GREETIN

    跟我学习javascript的prototype,getPrototypeOf和__proto__

    一、深入理解prototype, getPrototypeOf和_ proto _ prototype,getPropertyOf和 _ proto _ 是三个用来访问prototype的方法。它们的命名方式很类似因此很容易带来困惑。 它们的使用方式如下: C.prototype: 一般...

    浅谈javascript中的prototype和__proto__的理解

    在工作中有时候会看到prototype和__proto__这两个属性,对这两个属性我一直比较蒙圈,但是我通过查阅相关资料,决定做一下总结加深自己的理解,写得不对的地方还请各位大神指出。 跟__proto__属性相关的两个方法 ...

    帮你彻底搞懂JS中的prototype、__proto__与constructor(图解)

    这里说明一点,__proto__属性的两边是各由两个下划线构成(这里为了方便大家看清,在两下划线之间加入了一个空格:_ _proto_ _),实际上,该属性在ES标准定义中的名字应该是[[Prototype]],具体实现是由浏览器代理...

    prototype与__proto__区别详细介绍

    prototype与__proto__区别 Each constructor is a function that has a property named “prototype” that is used to implement prototype-based inheritance and shared properties. Every object created by a ...

    JavaScript中__proto__与prototype的关系深入理解

    一、所有构造器/函数的__proto__都指向Function.prototype,它是一个空函数(Empty function) 代码如下: Number.__proto__ === Function.prototype // true Boolean.__proto__ === Function.prototype // true ...

    LuaPbIntf:将Protobuf 3绑定到Lua 5.3

    LuaPbIntf Lua Protobuf界面。 使用lua-intf将Protobuf与Lua绑定,从而支持lua53和proto3。 LuaPbIntf的灵感来自 ,但已被重写以...luapb会跳过某些类型,例如:TYPE_SFIXED32。 见。 建立 用柯南构建 安装。 添

    cloud_project_miniProjet:TCP客户端,服务器,数据库连接proto-type_0.1

    cloud_project_miniProjet 这是第一个在双方之间传输字符串的TCP客户端/服务器应用程序的原型类型,也是使用Netbeans / IntellijIDea进行数据库交互的测试

    ProtoQuipper:Proto-Quipper 语言的实现

    这是 Proto-Quipper 的 README 文件。... -t, --type 不运行解释器。 -r, --run 运行解释(默认模式)。 -f FORMAT, --format=FORMAT 改变电路输出格式。 实现的格式是 *“visual”:在标准输出上显示电路 *

    JS原型prototype和__proto__用法实例分析

    本文实例讲述了JS原型prototype和__proto__用法。分享给大家供大家参考,具体如下: 先来看一个实例 function Foo() { } var foo = new Foo(); console.log(foo.prototype);// undefined console.log(foo.__proto__...

    JS中的原型以及prototype、constructor、__proto__三者之间的关系

    为什么要引入原型 如上图所示,我创建了两个对象person1 与 person2,这两个对象都要调用study 这个函数,这样就会在内存开辟两个study空间,但函数实现的功能都是一样的,所以这样太浪费内存空间了,所以原型的...

Global site tag (gtag.js) - Google Analytics