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,全称为 Tencent Neural Network,是腾讯公司推出的一款高效、轻量级的深度学习框架,主要用于移动设备和嵌入式平台上的机器学习任务。这个框架的设计目标是实现低功耗、高性能的模型部署,使得AI应用能够在...
type UserService interface { CreateUser(context.Context, *User) (*Response, error) } ``` 其中`User`和`Response`是定义的数据结构。 步骤3:手动编写或自动生成.proto文件 有两种方法来创建.proto文件: - ...
### Proto文件格式详解 #### 一、概述 在互联网产品开发过程中,前后端之间的数据交换极为重要。一种广泛采用的数据交换格式就是`protobuf`(Protocol Buffers),它为前后端提供了一种高效、灵活的数据传输手段。...
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。 可用于帮助生成到gRPC后端服务的GraphQL API网关。...}GraphQL type SearchRequest { query : String pageNumber : Int resultPerPage : Int}
描述net-proto软件包提供了一种获取协议信息的方法。... get_protocol ( 'icmp' ) # => 1# Using type specific methodsNet :: Proto . getprotobynumber ( 6 ) # => 'tcp'Net :: Proto . getprotob
当使用proto3协议时,一个常见的问题是空值字段不会在序列化为JSON时显示。这是因为proto3的设计原则之一是默认情况下忽略默认值,以减少网络传输的数据量。这在某些情况下可能会造成困扰,特别是当需要明确的JSON...
type greeterServer struct { helloworld.UnimplementedGreeterServer } func (s *greeterServer) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) { return &...
__proto__:每个对象都有一个名为__proto__的内部隐藏属性,指向于它所对应的原型对象(chrome、firefox中名称为__proto__,并且可以被访问到)。原型链正是基于__proto__才得以形成 (note:不是基于函数对象的属性...
pt-num:协议号pt-type:服务器| s | 客户| c pt-marco:宏名字pt-alias:协议号字符串(别名)pt注释:协议注释,插入解释方法前pt-content:协议内容key0:val0 key1:val1 keyx:valx 方法 gen_pt_marco2num.scm ...
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\...
17. **Type 19:**扩展 Class B CS 位置报告,提供比 Type 18 更多的详细信息。 18. **Type 20:**数据链路管理消息,用于管理 AIS 通信的数据链路层。 19. **Type 21:**助航设施报告,描述助航设施的状态和位置。 ...
在Protocol Buffer (简称Protobuf)中,我们可以通过`.proto`文件来定义消息结构。为了更好地理解这一过程,我们通过一个简单的示例来解释如何定义一个“搜索请求”消息格式。此消息包含一个查询字符串、感兴趣的查询...
__proto__是内部原型,prototype是构造器原型(构造器其实就是函数) 构造器的原型(prototype)是一个对象 那什么是构造器呢? 要想创建一个对象,首先要有一个对象构造器,就像php里面一样,要想创建一个对象,...
JavaScript中的`prototype`和`__proto__`是两个非常重要的概念,它们构成了JavaScript中的原型机制,是实现面向对象编程的基础。接下来,我们将深入探讨这两个属性以及它们之间的关系。 首先,`prototype`属性主要...
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
-G "Visual Studio 15 2017 Win64" -DCMAKE_BUILD_TYPE=Release ``` - 使用生成的解决方案文件打开protobuf项目,在Visual Studio中编译并安装。 3. **编译protobuf的protoc编译器** - 在Visual Studio中,找到...
一、深入理解prototype, getPrototypeOf和_ proto _ prototype,getPropertyOf和 _ proto _ 是三个用来访问prototype的方法。它们的命名方式很类似因此很容易带来困惑。 它们的使用方式如下: C.prototype: 一般...
JavaScript中的`prototype`、`__proto__`和`constructor`是理解JavaScript面向对象编程的关键概念。这篇文章将通过图解的方式帮助读者深入理解这三个属性的关系。 首先,`__proto__`属性,它存在于每个对象中,表示...
在工作中有时候会看到prototype和__proto__这两个属性,对这两个属性我一直比较蒙圈,但是我通过查阅相关资料,决定做一下总结加深自己的理解,写得不对的地方还请各位大神指出。 跟__proto__属性相关的两个方法 ...