java设计模式:prototype模式

prototype模式是在对象相似时使用。其是复制对象,并设置新的特征。


interface Prototype
{
	void setSize(int x);
	void printSize();
}

class A implements Prototype, Cloneable
{
	private int size;
	
	public A(int x)
	{
		this.size = x;
	}
	
	@Override
	public void setSize(int x)
	{
		this.size = x;
	}
	
	@Override
	public void printSize()
	{
		System.out.println("Size: " + size);
	}
	
	@Override
	public A clone() throws CloneNotSupportedException
	{
		return (A)super.clone();
	}
}

public class Main
{
	public static void main(String[] args) throws CloneNotSupportedException
	{
		A a = new A(1);
		
		for (int i = 2; i < 10; i++) {
			Prototype temp = a.clone();
			temp.setSize(i);
			temp.printSize();
		}
	}
}



你可能感兴趣的:(java设计模式:prototype模式)