package com.maom.design.D_06_Prototype;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @Title: D_06_Prototype
* @Description: 06_原型模式
* @Author maohb
* @Version 1.0
*/
public class D_06_Prototype implements Serializable{
public static void main(String[] args) {
// Person person1 = new Person();
// person1.setName("lifengxing");
// person1.setAge(30);
// person1.setSex("男");
//
Person person2 = person1;
// Person person2 = person1.clone();
//
// System.out.println(person1.getName());
// System.out.println(person1.getAge());
// System.out.println(person1.getSex());
//
// System.out.println(person2.getName());
// System.out.println(person2.getAge());
// System.out.println(person2.getSex());
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());
}
}
class Person implements Cloneable{
// 姓名
private String name;
// 年龄
private int age;
// 朋友
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 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;
}
}
}
设计模式笔记_06_原型模式
最新推荐文章于 2024-09-08 21:56:57 发布