具体的实现代码的demo:
样例为克隆一只羊:
public class Sheep implements Cloneable{
private String name;
private int age;
private String color;
@Override
protected Object clone() {
Sheep sheep =null;
try {
sheep = (Sheep)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return sheep;
}
public Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
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 getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Sheep{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
}
测试代码:
/**
* 原型模式的好处:当对象sheep 的属性值有变化的时候,无需动原来的代码
*/
public class SheepTest {
public static void main(String[] args) {
Sheep sheep = new Sheep("tom",3,"white");
Object sheep1 = (Sheep)sheep.clone();
Object sheep2 = (Sheep)sheep.clone();
System.out.println(sheep1);
System.out.println(sheep2);
}
}
输出结果:
Sheep{name='tom', age=3, color='white'}
Sheep{name='tom', age=3, color='white'}
Spring源码中运用到该模式的地方,如下截图: