1.说明
原型(Prototype)模式的定义如下:用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。在这里,原型实例指定了要创建的对象的种类。用这种方式创建对象非常高效,根本无须知道对象创建的细节。
1.结构
由于 Java 提供了对象的 clone() 方法,所以用 Java 实现原型模式很简单。
原型模式包含以下主要角色。
2.图

3.程序实现
//具体原型类
class Realizetype implements Cloneable
{
Realizetype()
{
System.out.println("具体原型创建成功!");
}
public Object clone() throws CloneNotSupportedException
{
System.out.println("具体原型复制成功!");
return (Realizetype)super.clone();
}
}
//原型模式的测试类
public class PrototypeTest
{
public static void main(String[] args)throws CloneNotSupportedException
{
Realizetype obj1=new Realizetype();
Realizetype obj2=(Realizetype)obj1.clone();
System.out.println("obj1==obj2?"+(obj1==obj2));
}
}
1.步骤
先让引用的对象实现Cloneable
然后再调用的对象里重新赋值
2.程序
package com.jun.design.psknowledge;
import lombok.Data;
@Data
public class Person implements Cloneable{
private String name;
private Integer age;
private Address address;
@Override
protected Object clone() throws CloneNotSupportedException {
Person person = (Person)super.clone();
person.address = (Address)address.clone();
return person;
}
}
package com.jun.design.psknowledge;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Address implements Cloneable{
/**
* 省
*/
private String province;
/**
* 市
*/
private String city;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package com.jun.design.psknowledge;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
deepCopy();
}
private static void deepCopy() throws CloneNotSupportedException {
Person person = new Person();
person.setName("tom");
person.setAge(20);
person.setAddress(new Address("江苏", "南京"));
Person clonePerson = (Person)person.clone();
clonePerson.setAge(22);
System.out.println(clonePerson);
}
}
效果:
Connected to the target VM, address: ‘127.0.0.1:53519‘, transport: ‘socket‘ Person(name=tom, age=22, address=Address(province=江苏, city=南京)) Disconnected from the target VM, address: ‘127.0.0.1:53519‘, transport: ‘socket‘ Process finished with exit code 0
原文:https://www.cnblogs.com/juncaoit/p/13438548.html