设计模式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();
		}

	}

}



你可能感兴趣的:(design,pattern)