原型模式
public class Phone implements Cloneable {
private String toPhoneNumber; // 去电号码
private String context; // 内容
private String hello; // 称谓
@Override
public Phone clone() {
try {
return (Phone) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public Phone(Man man) {
this.context = man.getContext();
this.hello = man.getHello();
}
geter/setter
}
public class Man {
private String hello = "先生您好,";
private String context = "需要剃须刀吗?";
geter
}
public class Prototype {
public static void main(String... args) {
int i = 0;
Phone phone = new Phone(new Man());
while (i <= 5) {
Phone clone = phone.clone();
phone.setToPhoneNumber(getRandString(11));
call(clone);
i++;
}
}
private static String getRandString(int maxLength) {
String source = "0123456789";
StringBuffer sb = new StringBuffer();
Random rand = new Random();
for (int i = 0; i < maxLength; i++) {
sb.append(source.charAt(rand.nextInt(source.length())));
}
return sb.toString();
}
private static void call(Phone phone) {
System.out.println("给" + phone.getToPhoneNumber() + "打电话:" + phone.getHello() + phone.getContext());
}
}
很简单的原型模式
原型模式的优点
- 性能优良
- 逃避构造函数的约束
原型模式的使用场景
资源优化场景
类初始化需要消化非常多的资源,这个资源包括数据、硬件资源等。
性能和安全要求的场景
通过new产生一个对象需要非常繁琐的数据准备或访问权限,则可以使用原型模式。
一个对象多个修改者的场景
注意
使用clone方法,在类的成员变量上就不要增加final关键字
学习之余也不要忘了劳逸结合哦
喜欢天马行空的同学请关注公众号:
还没有评论,来说两句吧...