作用:
用原型实例指定创建对象的种类,并且通过复制(克隆)这些原型创建新对象。
关键点:
1.Prototype(抽象原型类)他是声明克隆方法的接口,是所有具体原型的公共父类,可以是抽象类也可以是接口,甚至还可以是具体实现类。
2.ConcretePrototype(具体原型类):它实现在抽象原型类中声明的方法,在克隆方法中返回自己的一个克隆对象
3.Client(客户端);让一个原型对象克隆自身从而创建一个全新的对象。
扩展(深浅克隆、拷贝 object对象的clone方法)
一、接口方式的原型模式
// 1 接口
package com.lpw.prototype;
public interface Resume {
public Resume clone();
}
package com.lpw.prototype;
public class ConcreteResume implements Resume{
@Override
public Resume clone() {
Resume resume = new ConcreteResume();
return resume;
}
}
package com.lpw.prototype;
public class Client {
public static void main(String[] args) {
// 原型实例,把复制过程隐藏起来
Resume resume = new ConcreteResume();
resume.clone();
}
}
二、通过实体类实现原型模式
package com.lpw.prototype1;
// 简历
public class Resume implements Cloneable{
private String name;
private int age;
private String [] hobby;
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[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public Resume() {
super();
// TODO Auto-generated constructor stub
}
public Resume(String name, int age, String[] hobby) {
super();
this.name = name;
this.age = age;
this.hobby = hobby;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
package com.lpw.prototype1;
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
// 原型实例,把复制过程隐藏起来
Resume resume = new Resume();
resume.clone();
}
}
使用场景:
构造函数非常复杂
解通过new产生一个对象需要非常繁琐的数据准备
讲解例子
String name
int age
String[] hibby
注意事项:
对象拷贝时构造函数没有进行执行,这点从原理来讲也是可以讲的通的,Object类的clone方法的原因是从内存中(具体地说就是堆内存)以二进流的方式进行拷贝,重新分配一个内存块
在java虚拟机中,只有实现了这个接口(Cloneable)的类才可以被拷贝,否则在运行时掏ChooNotSupportedException。