设计模式之原型模式

定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

结构图:

设计模式之原型模式_第1张图片

示例代码:略

提示 在实际的Java应用中,我们在复杂一个对象的时候,是要重写这个对象所对应类的clone方法,但clone这个方法是protected,其它类不对直接调用,因此在实际的应用中,要复制一个对象,多数是用字节流来实现的,具体代码如下:

package com.tds.clone.bean;

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

public class CloneBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8966450834831993043L;
	private int x;
	private int y;

	public CloneBean(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	@Override
	public Object clone() throws CloneNotSupportedException {

		try {
			// 字节流输出数组
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream object_os = new ObjectOutputStream(byteArrayOutputStream);
			object_os.writeObject(this);
			
			byte[] obj_byte = byteArrayOutputStream.toByteArray();
			
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(obj_byte);
			ObjectInputStream object_is = new ObjectInputStream(byteArrayInputStream);
			CloneBean cloneBean = (CloneBean)object_is.readObject();
			return cloneBean;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) throws CloneNotSupportedException {
		
		CloneBean cloneBean1 = new CloneBean(1, 2);
		CloneBean cloneBean2 = (CloneBean)cloneBean1.clone(); 
		cloneBean1.setX(2);
		cloneBean1.setY(3);
		System.out.println("old X: " + cloneBean1.getX());
		System.out.println("old Y: " + cloneBean1.getY());
		
		System.out.println("new X: " + cloneBean2.getX());
		System.out.println("new Y: " + cloneBean2.getY());
	}
}

运行的结果如下:

old X: 2
old Y: 3
new X: 1
new Y: 2

说明,对象是真的被复制了


你可能感兴趣的:(设计模式之原型模式)