1.概念:
原型模式(Prototype Pattern)是通过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的办法创建出更多的同类对象,同时又能保证性能而且不需要知道内部细节。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
在运行期建立和删除原型。
利用已有的一个原型对象,快速地生成和原型对象一样的实例。
缺点:
使用场景:
注意事项: 与通过对一个类进行实例化来构造新对象不同的是,原型模式是通过拷贝一个现有对象生成新对象的。浅拷贝实现 Cloneable,重写,深拷贝是通过实现 Serializable 读取二进制流。
原型模式的 UML 图
订单处理系统 现在有一个订单处理系统,里面有一个保存订单的业务功能,需求:每当订单的预定产品数量超过1000的时候,就需要把订单拆成两份订单来保存。如果拆成两份后还是超过1000,则继续拆分,直到每份产品预订数量不超过1000.
package 原型模式;
public class Product implements Cloneable {
private String ID;
private String Name;
public String show() {
return "产品ID为:"+ID+"产品名称为:"+Name;
}
public Product(String iD, String name) {
ID = iD;
Name = name;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public Object clone()
{
Object clone=null;
try {
clone=super.clone();
}catch(Exception E)
{
E.printStackTrace();
}
return clone;
}
}
package 原型模式;
public class Bill {
private String Str_type;
private Product Pro_pro;
private int int_number;
public Bill(String iD, String name, String str_type , int int_number) {
Pro_pro=new Product(iD,name);
Str_type = str_type;
this.int_number = int_number;
}
public Object clone()
{
Object clone=null;
try {
clone=super.clone();
}catch(Exception E)
{
E.printStackTrace();
}
return clone;
}
public String show()
{
return "订单类型:"+Str_type+"数量:"+int_number+Pro_pro.show();
}
public void setPro(String ID,String name)
{
Pro_pro=new Product(ID,name);
}
public String getStr_type() {
return Str_type;
}
public void setStr_type(String str_type) {
Str_type = str_type;
}
public Product getPro_pro() {
return Pro_pro;
}
public void setPro_pro(Product pro_pro) {
Pro_pro = pro_pro;
}
public int getInt_number() {
return int_number;
}
public void setInt_number(int int_number) {
this.int_number = int_number;
}
}
package 原型模式;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("请设置订单信息:产品ID 产品名称 订单类型 数量");
String s1,s2,s3;
int num;
Scanner in = new Scanner(System.in);
s1=in.next();
s2=in.next();
s3=in.next();
num=in.nextInt();
Bill b1=new Bill(s1,s2,s3,num);
Bill b2[]=new Bill[50];
System.out.println(b2.length);
int n=0;
while(b1.getInt_number()>1000)
{
b2[n]=b1;
b2[n].setInt_number(b1.getInt_number()-1000);
b2[n++].setInt_number(1000);
}
b2[n]=b1;
System.out.println(b1.show());
for (int i = 0; i <=n; i++) {
System.out.println(b2[i].show());
}
in.close();
}
}
写在最后: 我叫风骨散人,名字的意思是我多想可以不低头的自由生活,可现实却不是这样。家境贫寒,总得向这个世界低头,所以我一直在奋斗,想
改变我的命运
给亲人好的生活,希望同样被生活绑架的你
可以通过自己的努力改变现状,深知成年人的世界里没有容易二字。目前是一名在校大学生,预计考研,热爱编程,热爱技术,喜欢分享,知识无界,希望我的分享可以帮到你! 如果有什么想看的,可以私信我,如果在能力范围内,我会发布相应的博文! 谢谢大家的阅读!?