天天看点

Java设计模式:原型模式

什么是原型模式

原型模式是一种对象创建型模式,它采取复制原型对象的方法来创建对象的实例。使用原型模式创建的实例,具有与原型一样的数据。

原型模式的特点

  1. 由原型对象自身创建目标对象。也就是说,对

    象创建这一动作发自原型对象本身。

  2. 目标对象是原型对象的一个克隆。也就是说,

    通过Prototype模式创建的对象,不仅仅与原型

    对象具有相同的结构,还与原型对象具有相同的

    值。

  3. 根据对象克隆深度层次的不同,有浅度克隆与

    深度克隆。

实现步骤

  • 继承接口Cloneable,并实现clone方法,

    注意: 如果属性只是基本数据类型,那只需要浅克隆,调用

    super.clone()

    方法即可,如果属性是对象,那么需要深度克隆,新建一个属性对象,将原型的数据复制到新属性对象,再将其赋值给克隆的对象
public class Person implements Cloneable{

	private String name;

	private int age;

	private String sex;

	private List<String> friends;

	public List<String> getFriends() {
		return friends;
	}

	public void setFriends(List<String> friends) {
		this.friends = friends;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

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

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
	
	public Person clone() {
		try {
			Person person  = (Person)super.clone();
			List<String> newfriends = new ArrayList<String>();
			for(String friend : this.getFriends()) {
				newfriends.add(friend);
			}
			person.setFriends(newfriends);
			return  person;
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			return null;
		}
	}
}
           
  • 在main方法中创建对象并克隆,可以看出克隆出来的是两个数据一样的,但是不是同一引用的对象。
public class MainClass {
	public static void main(String[] args) {	
		Person person1 = new Person();
		List<String> friends = new ArrayList<String>();
		friends.add("James");
		friends.add("Yao");
		person1.setFriends(friends);	
		Person person2 = person1.clone();	
		System.out.println(person1.getFriends());
		System.out.println(person2.getFriends());	
		friends.add("Mike");
		person1.setFriends(friends);
		System.out.println(person1.getFriends());
		System.out.println(person2.getFriends());
	}
}
           
  • 输出结果
    Java设计模式:原型模式