设计模式prototype(原型模式)

原型接口:

package prototype;

public interface Prototype {
	public Object cloneMe() throws CloneNotSupportedException;

}

浅拷贝实现:

package prototype;

//立方体
public class Cubic implements Prototype,Cloneable{
	double length,width,height;

	Cubic(double length, double width, double height) {
		this.length = length;
		this.width = width;
		this.height = height;
	}

	//以浅拷贝的方式实现(Object类中的clone是浅拷贝)
	@Override
	public Object cloneMe() throws CloneNotSupportedException {
		Cubic object=(Cubic)clone();//Object的clone()方法
		return object;
	}

}

深拷贝实现:

package prototype;

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 Goat implements Prototype,Serializable {
	StringBuffer color;

	public StringBuffer getColor() {
		return color;
	}

	public void setColor(StringBuffer color) {
		this.color = color;
	}

	//以深度拷贝方式实现
	@Override
	public Object cloneMe() throws CloneNotSupportedException {
		Object object=null;
		
		try {
			ByteArrayOutputStream outOne=new ByteArrayOutputStream();
			ObjectOutputStream outTwo=new ObjectOutputStream(outOne);
			outTwo.writeObject(this);
			ByteArrayInputStream inOne=new ByteArrayInputStream(outOne.toByteArray());
			ObjectInputStream inTwo=new ObjectInputStream(inOne);
			object=inTwo.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return object;
	}

}

测试:

package prototype;

public class Application {
	
	public static void main(String[] args) {
		Cubic cubic=new Cubic(12, 20, 66);
		System.out.println("cubic 的长 、宽、高:");
		System.out.println(cubic.length+","+cubic.width+","+cubic.height);
		
		try {
			Cubic cubicCopy=(Cubic) cubic.cloneMe();
			System.out.println("cubicCopy 的长 、宽、高:");
			System.out.println(cubicCopy.length+","+cubicCopy.width+","+cubicCopy.height);
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		
		Goat goat=new Goat();
		goat.setColor(new StringBuffer("白颜色的山羊"));
		System.out.println("goat是"+goat.getColor());
		
		try {
			Goat goatCopy=(Goat) goat.cloneMe();
			System.out.println("goatCopy是"+goatCopy.getColor());
			System.out.println("颜色变为黑色");
			goatCopy.setColor(new StringBuffer("黑颜色的山羊"));
			System.out.println("goat是"+goat.getColor());
			System.out.println("goatCopy是"+goatCopy.getColor());
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值