介绍
- 原型模式(Prototype模式)指:用原型实例指定创建的种类,并且通过拷贝这些原型,创建新的对象
- 原型模式是哟中创建型设计模式,允许一个对象超级爱你再超级爱你另一个可定制的对象,无需知道创建的细节
- 工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建爱你,即 对象.clone()
- Prototype : 为原型类,声明一个克隆自身的接口
- ConcretePrototype : 为具体实现类,实现一个克隆自身的操作;而客户端Client只需让一个原型克隆自身,从而创建一个新的对象。
案例
- 现在有一只羊tom ,姓名为 :tom,颜色为:白色,请编写程序创建和tom羊完全属性相同的10只羊
之前的写法 :
新建Sheep 类
@Data
public class Sheep {
//姓名
private String name;
//年龄
private Integer age;
//颜色
private String color;
public Sheep(String name, Integer age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
}
编写测试类
public class Test {
public static void main(String[] args) {
Sheep sheep =new Sheep("tom",1,"白色");
Sheep sheep2 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep3 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
Sheep sheep4 = new Sheep(sheep.getName(),sheep.getAge(),sheep.getColor());
System.out.println(sheep);
System.out.println(sheep2);
System.out.println(sheep3);
System.out.println(sheep4);
}
}
- 传统方式解决克隆羊的问题
- 有点好理解,简单
- 在创建新的对象的时候,总是需要重新获取原始对象的属性,如果创建对象复杂,效率低,不够灵活
使用原型模式 代码改造
@Data
public class Sheep implements Cloneable{
//姓名
private String name;
//年龄
private Integer age;
//颜色
private String color;
public Sheep(String name, Integer age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
//克隆该实例,默认实用化clone方法来完成
@Override
protected Object clone() throws CloneNotSupportedException {
Sheep sheep = null;
sheep =(Sheep)super.clone();
return sheep;
}
public static void main(String[] args) throws CloneNotSupportedException {
Sheep sheep =new Sheep("tom",1,"白色");
Sheep sheep2= (Sheep) sheep.clone();
System.out.println(sheep);
System.out.println(sheep2);
}
优点和缺点
优点:
1)性能优良。不用重新初始化对象,而是动态地获取对象运行时的状态。
2)逃避构造函数的约束。
缺点:
1)配置克隆方法需要对类的功能进行通盘考虑。
2)必须实现Cloneable接口。
适用场景:
1) 一般与工厂方法模式一起出现,通过clone方法创建一个对象,然后由工厂方法提供给调用者。
- 原型模式在Spring框架中应用
//已原型模式创建
<bean id ="id" class="com.yxl.bean.Monster" scope="prototype">
github Demo地址 : ~~~传送门~~~
个人博客地址:http://blog.yanxiaolong.cn/