设计模式主要分创建型模式、结构型模式和行为型模式。
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
例子:JAVA 中的 Object clone() 方法。
核心思想:通过拷贝原型对象创建新对象
1.浅拷贝实现
public class Person implements Cloneable {
private String name;
private Computer computer;
public Person(String name, Computer computer) {
//clone 不会进入构造方法
this.name = name;
this.computer = computer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Computer getComputer() {
return computer;
}
public void setComputer(Computer computer) {
this.computer = computer;
}
@Override
protected Object clone() {
Person person = null;
try {
person = (Person) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return person;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", computer=" + computer +
'}';
}
}
public class Computer implements Cloneable {
private String color;
public Computer(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Computer{" +
"color='" + color + '\'' +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Client {
public static void main(String[] args) {
Computer computer = new Computer("red");
Person prototype = new Person("hello test", computer);
Person clone = (Person) prototype.clone();
System.out.println("prototype" + prototype.toString());
System.out.println("clone: " + clone.toString());
}
}
//输出结果为
prototypePerson{name='hello test', computer=Computer{color='red'}}
clone: Person{name='hello test', computer=Computer{color='red'}}
注这种方式是时不安全的。clone只拷贝你指定的对象,至于你指定的对象里面的别的对象,它不拷贝,还是把引用给你
内部的数组和引用对象不会拷贝,其他的原始基本类型和String类型会被拷贝
public class Client {
public static void main(String[] args) {
Computer computer = new Computer("red");
Person prototype = new Person("hello test", computer);
Person clone = (Person) prototype.clone();
prototype.getComputer().setColor("我改变了computer对象的值");
System.out.println("prototype" + prototype.toString());
System.out.println("clone: " + clone.toString());
}
}
//如果在内存中改变Computer的值得话输出:
prototypePerson{name='hello test', computer=Computer{color='我改变了computer对象的值'}}
clone: Person{name='hello test', computer=Computer{color='我改变了computer对象的值'}}
2.深拷贝
通过成员内部属性的clone方法
@Override
protected Object clone() {
Person person = null;
try {
person = (Person) super.clone();
//调用内部属性的clone方法
this.computer= (Computer) computer.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return person;
}
通过序列化对象
//对内部对象属性增加序列化和反序列化