Design pattern (6) prototype pattern

It is a ready-made object, which has designed values
When I want to create a new object and assign the same value to the new object

1. shallow copy

There are only 9 data types that can be copied directly. The basic data types of java + string. The copies of list and map are reference addresses and shallow copies. If you want to copy deeply, you must make list go to clone as well

import java.util.ArrayList;
import java.util.List;

public class ConcretePrototype extends Prototype{
	private int age;
	
	public List<String> list =new ArrayList<String>();

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
		

}
public class Prototype implements Cloneable{

	protected Object clone() throws CloneNotSupportedException {
		return super.clone();
	}

}
import java.util.ArrayList;
import java.util.List;

public class Main {
public static void main(String[] args) {
	ConcretePrototype cp=new ConcretePrototype();
	cp.setAge(18);
	
	cp.list.add("1");
	
	try {
		ConcretePrototype copy=(ConcretePrototype) cp.clone();
		System.out.println(copy.getAge());
		System.out.println(cp==copy);//Not the same object
		System.out.println(cp.list==copy.list);//list points to the same address, unreasonable, shallow copy
	} catch (CloneNotSupportedException e) {
		e.printStackTrace();
	}
}
}



//There are only 9 data types that can be copied directly. The basic data types of java + string. The copies of list and map are reference addresses and shallow copies. If you want to copy deeply, you must make list go to clone as well





2. deep copy

import java.util.ArrayList;

public class Prototype implements Cloneable{
	
	public ArrayList<String> list =new ArrayList<String>();

	@SuppressWarnings("unchecked")
	protected Object clone() throws CloneNotSupportedException {
		Prototype prototype=null;
		prototype=(Prototype) super.clone();
		prototype.list=(ArrayList<String>) list.clone();
		return prototype;
	}

}

 

public class ConcretePrototype extends Prototype{
	private int age;
	
	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
		

}
public class Main {
public static void main(String[] args) {
	ConcretePrototype cp=new ConcretePrototype();
	cp.setAge(18);
	
	cp.list.add("1");
	
	try {
		ConcretePrototype copy=(ConcretePrototype) cp.clone();
		System.out.println(copy.getAge());
		System.out.println(cp==copy);//Not the same object
		System.out.println(cp.list==copy.list);//list points to different addresses, deep copy
	} catch (CloneNotSupportedException e) {
		e.printStackTrace();
	}
}
}

3. If a list contains a map and a map contains a list, you need to use a loop or reflection

Keywords: Java

Added by khushbush on Thu, 13 Feb 2020 21:53:28 +0200