1、原型模式的概念:
用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象
2、类型:创建型类型
3、简介:
原型模式主要用于对象的复制,他的核心就是原型类Prototype,其中Prototype类具备以下两个条件:
1)实现Cloneable接口。在java语言中有Cloneable这个接口,它的作用只有一个就是对实现该接口的类通知JVM可以安全的使用该接口定义的类中的clone方法,
2)重写Object中的clone方法,java中所有类的父类都是Object,Object类中有一个clone方法,作用是返回对象的一个拷贝,但是其作用域是protected的,所以一般需要将Prototype转换成public类进行实现。
3)需要被克隆的类必须继承这个类。
4、具体实现
1)prototype
package com.jxau.ruanjian1201.Pattern.Prototype;
import java.util.ArrayList;
public class Prototype implements Cloneable {
private ArrayList list = new ArrayList();
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype) super.clone();
prototype.list = (ArrayList) this.list.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return prototype;
}
}
2)Bean.java原型模式实现类
package com.jxau.ruanjian1201.Pattern.Prototype;
public class Bean extends Prototype{
private String name;
private int age;
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 static void main(String[] args) {
Bean bean = new Bean();
bean.setAge(22);
bean.setName("linhao007");
Bean bean1 = (Bean) bean.clone();//原型模式创建对象
System.out.println(bean1.getName());
}
}
5、适用场景和优点
1)使用原型模型,使的jvm直接操作内存中的二进制流,并进行拷贝,并不需要new出内存加以操作,而且不会执行查找构造方法链去创建对象,因此大数据封装到对象中并遍历的时候运用原型模式可以大大提高效率
2)使用原型模式的另一个作用就是简化对象,所以在需要重复的创建相似对象可以考虑使用原型模式,就比如在一个循环体内创建对象时候,循环次数比较多的时候可以采用这种模式。