Java设计模式 —— 原型模式(Proto Type)

PROTOTYPE—跟MM用QQ聊天,一定要说些深情的话语了,我搜集了好多肉麻的情话,需要时只要copy出来放到QQ里面就行了,这就是我的情话prototype了。(100块钱一份,你要不要)

原始模型模式:通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的方法创建出更多同类型的对象。原始模型模式允许动态的增加或减少产品类,产品类不需要非得有任何事先确定的等级结构,原始模型模式适用于任何的等级结构。缺点是每一个类都必须配备一个克隆方法。

通过一个原型对象来创建一个新对象(克隆)。Java中要给出Clonable接口的实现,具体类要实现这个接口,并给出clone()方法的实现细节,这就是简单原型模式的应用。 

浅拷贝:只拷贝简单属性的值和对象属性的地址 

深拷贝:拷贝本对象引用的对象,有可能会出现循环引用的情况。可以用串行化解决深拷贝。写到流里再读出来,这时会是一个对象的深拷贝结果。

package com.modes;

import java.io.*;

/*
 * 原型模式(ProtoType)
 */
public class TestClonealbe {
	public static void main(String[] args) throws Exception {
		Father f = new Father();
		User u1 = new User("123456",f);
		User u2 = (User)u1.clone();
		
		System.out.println(u1==u2);
		System.out.println(u1.password.equals(u2.password));
		System.out.println(u1.f==u2.f);
		System.out.println(u1.f.equals(u2.f));
	}
}

class User implements Cloneable,Serializable {
	String password;
	Father f;
	
	public User(String password, Father f) {
		this.password = password;
		this.f = f;
	}
	
	public Object clone() throws CloneNotSupportedException {
		ObjectOutputStream out = null;
		ObjectInputStream in = null;
		
		try {
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			out = new ObjectOutputStream(bo);
			out.writeObject(this); // /Clone this object
			out.flush();
			byte[] bs = bo.toByteArray();
			ByteArrayInputStream bi = new ByteArrayInputStream(bs);
			in = new ObjectInputStream(bi);
			Object o = in.readObject();
			
			return o;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

class Father implements Serializable {
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值