設計模式學習-原型模式

       原型模式是一種對象創建型模式,它採取複製原型對象的方法來創建對象的實例。使用原型模式創建的實例,具有與原型一樣的數據。原型模式可以看作原型對象對自身的一個克隆。根據對象克隆深度層次的不同,有淺度克隆與深度克隆。

       下面看原型模式結構圖(摘自 程傑 大話設計模式)

 

下面利用java實現原型模式

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;
		}
	}

}

      Person 實現 Cloneable接口,聲明一個克隆自身的接口。實現 clone() 方法。實現Cloneable接口後 調用 Objecte的clone()方法,可以實現淺度克隆,淺度克隆指的是 只複製了值類型的字段屬性,對於引用類的字段屬性,複製引用但不復制引用的對象。原始對象與副本引用同一對象。如例子中的 List<String> friends ,所以要實現深複製只能自己動手在方法clone中實現。

下面是執行

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());
	}
}

對於原型模式一定要把握複製的層數,若是層數越多,就越複雜。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章