THEEYE 2020-03-26
一、基本概念
1、原型模式(Prototype模式)是指:用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象 。
2、角色:
A、抽象原型(Prototype)角色:此角色定义了的具体原型类所需的实现的方法,本例子直接精简为类。
B、客户(Client)角色:客户类提出创建对象的请求;也就是我们用户使用复制粘贴的功能。
3、其实原型模式的核心就是Prototype(抽象原型),他需要继承Cloneable接口,并且重写Object类中的clone方法即可。
二、简单例子
A、抽象原型(Prototype)角色:
package comm.pattern.create.prototype;
import java.util.HashMap;
import java.util.Map.Entry;
/**
*
* @Title: ProtoTypeClass.java
* @Package: comm.pattern.create.prototype
* @Description: 描述该文件做什么
* @author yangzhancheng
* @2020年3月25日:下午10:27:15
*
*/
public class PersonProtoType implements Cloneable {
// 年龄
private int age;
// 姓名
private String name;
// 朋友链
private HashMap<String, String> FriendsName = new HashMap<String, String>();
// 朋友链
private HashMap<String, PersonProtoType> Friends = new HashMap<String, PersonProtoType>();
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public HashMap<String, String> getFriendsName() {
return FriendsName;
}
public void setFriendsName(HashMap<String, String> friendsName) {
FriendsName = friendsName;
}
public HashMap<String, PersonProtoType> getFriends() {
return Friends;
}
public void setFriends(HashMap<String, PersonProtoType> friends) {
Friends = friends;
}
@Override
public PersonProtoType clone() {
PersonProtoType clone = null;
try {
clone = (PersonProtoType)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
// 返回字符串
@Override
public String toString() {
StringBuffer strbuff = new StringBuffer();
strbuff.append("name:" + this.name);
strbuff.append(",age:" + this.age);
for (Entry<String, String> entry : this.FriendsName.entrySet()) {
String columnName = entry.getKey();
String value = entry.getValue();
strbuff.append("\n第" + columnName + "个朋友;" + value);
}
return strbuff.toString();
}
}B、客户(Client)角色:
package comm.pattern.create.prototype;
import java.util.HashMap;
/**
*
* @Title: Client.java
* @Package: comm.pattern.create.prototype
* @Description: 描述该文件做什么
* @author yangzhancheng
* @2020年3月25日:下午10:34:05
*
*/
public class Client {
public static void main(String[] args) {
PersonProtoType person = new PersonProtoType();
person.setAge(24);
person.setName("丽丽");
HashMap<String, String> friendsName = new HashMap<String, String>();
friendsName.put("1", "小马");
friendsName.put("2", "小李");
person.setFriendsName(friendsName);
System.out.println("输出原来人物:\n"+person.toString());
//克隆
System.out.println("---------------------------------------");
PersonProtoType coppyperson = person.clone();
System.out.println("输出复制人物:\n"+coppyperson.toString());
}
}运行结果
输出原来人物: name:丽丽,age:24 第1个朋友;小马 第2个朋友;小李 --------------------------------------- 输出复制人物: name:丽丽,age:24 第1个朋友;小马 第2个朋友;小李
三、总结
注意:java执行clone方法的时候是直接从内存中去获取数据的,在第一次创建对象的时候就会把数据在内存保留一份,克隆的时候直接调用就好了,因此不初始化构造方法。