在应用程序开发中,管理对象创建可能很复杂,特别是在处理几乎相同但具体细节有所不同的实例时。原型设计模式提供了一种解决方案,允许我们通过复制或“克隆”现有对象来创建新对象。当对象的创建成本高昂或涉及大量初始化时,此模式特别有用。
在本文中,我们将使用实际的电子商务用例来探索如何在 spring boot 应用程序中实现原型设计模式:创建和保留产品变体。通过这个示例,您不仅可以了解原型模式的基础知识,还可以了解它如何简化实际应用程序中的对象创建。
原型模式是一种创建型设计模式,允许您通过克隆现有对象(称为原型)来创建新实例。当您拥有具有各种属性的基础对象时,这种方法特别有用,并且从头开始创建每个变体将是多余且低效的。
在 java 中,这种模式通常使用 cloneable 接口或定义自定义克隆方法来实现。主要思想是提供一个可以通过修改进行复制的“蓝图”,保持原始对象完整。
减少初始化时间:您无需从头开始创建对象,而是克隆和修改现有实例,从而节省初始化时间。
封装对象创建逻辑:您可以定义如何在对象本身内克隆对象,同时隐藏实例化详细信息。
增强性能:对于经常创建类似对象(例如产品变体)的应用程序,原型模式可以提高性能。
想象一个电子商务平台,其中基本产品具有各种配置或“变体” - 例如,具有不同颜色、存储选项和保修条款的智能手机。我们可以克隆基础产品,然后根据需要调整特定字段,而不是从头开始重新创建每个变体。这样,共享属性保持一致,我们只修改特定于变体的细节。
在我们的示例中,我们将构建一个简单的 spring boot 服务,以使用原型模式创建和保存产品变体。
首先定义一个产品类,其中包含产品的必要字段,例如 id、名称、颜色、型号、存储、保修和价格。我们还将添加一个 cloneproduct 方法来创建产品的副本。
public interface productprototype extends cloneable {
productprototype cloneproduct();
}
@entity
@table(name = "products")
@data
public class product implements productprototype {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
@column(name = "product_id")
private long productid;
@column(name = "name")
private string name;
@column(name = "model")
private string model;
@column(name = "color")
private string color;
@column(name = "storage")
private int storage;
@column(name = "warranty")
private int warranty;
@column(name = "price")
private double price;
@override
public productprototype cloneproduct() {
try {
product product = (product) super.clone();
product.setid(null); // database will assign new id for each cloned instance
return product;
} catch (clonenotsupportedexception e) {
return null;
}
}
}
在此设置中:
cloneproduct: 此方法创建 product 对象的克隆,并将 id 设置为 null 以确保数据库为每个克隆实例分配一个新 id。
接下来,创建一个具有保存变体方法的 productservice。此方法克隆基础产品并应用特定于变体的属性,然后将其另存为新产品。
public interface productservice {
// for saving the base product
product savebaseproduct(product product);
// for saving the variants
product savevariant(long baseproductid, variantrequest variant);
}
@log4j2
@service
public class productserviceimpl implements productservice {
private final productrepository productrepository;
public productserviceimpl(productrepository productrepository) {
this.productrepository = productrepository;
}
/**
* saving base product, going to use this object for cloning
*
* @param product the input
* @return product object
*/
@override
public product savebaseproduct(product product) {
log.debug("save base product with the detail {}", product);
return productrepository.save(product);
}
/**
* fetching the base product and cloning it to add the variant informations
*
* @param baseproductid baseproductid
* @param variant the input request
* @return product
*/
@override
public product savevariant(long baseproductid, variantrequest variant) {
log.debug("save variant for the base product {}", baseproductid);
product baseproduct = productrepository.findbyproductid(baseproductid)
.orelsethrow(() -> new nosuchelementexception("base product not found!"));
// cloning the baseproduct and adding the variant details
product variantdetail = (product) baseproduct.cloneproduct();
variantdetail.setcolor(variant.color());
variantdetail.setmodel(variant.model());
variantdetail.setwarranty(variant.warranty());
variantdetail.setprice(variant.price());
variantdetail.setstorage(variant.storage());
// save the variant details
return productrepository.save(variantdetail);
}
}
在此服务中:
savevariant:此方法通过 id 检索基本产品,克隆它,应用变体的详细信息,并将其保存为数据库中的新条目。
创建一个简单的 rest 控制器来公开变体创建 api。
@restcontroller
@requestmapping("/api/v1/products")
@log4j2
public class productcontroller {
private final productservice productservice;
public productcontroller(productservice productservice) {
this.productservice = productservice;
}
@postmapping
public responseentity<product> savebaseproduct(@requestbody product product) {
log.debug("rest request to save the base product {}", product);
return responseentity.ok(productservice.savebaseproduct(product));
}
@postmapping("/{baseproductid}/variants")
public responseentity<product> savevariants(@pathvariable long baseproductid, @requestbody variantrequest variantrequest) {
log.debug("rest request to create the variant for the base product");
return responseentity.ok(productservice.savevariant(baseproductid, variantrequest));
}
}
这里:
网站前台采用主流页面设计,主站模版布局时尚、新颖。用户注册系统采用一站通的模式,用户可以实现在线购物和开店以及帐户管理。 用户中心界面友好、操作简洁方便,采取清晰的分项管理:即可以分别管理【我是买家】、【我是卖家】、【帐户管理】三大项目。
548
savevariant: 此端点处理 http post 请求以创建指定产品的变体。它将创建逻辑委托给 productservice。
通过此实施,我们看到了几个明显的优势:
代码可重用性:通过将克隆逻辑封装在 product 类中,我们避免了服务和控制器层中的代码重复。
简化维护:原型模式集中了克隆逻辑,可以更轻松地管理对象结构的更改。
高效变体创建:每个新变体都是基础产品的克隆,减少冗余数据输入并确保共享属性的一致性。
./gradlew build ./gradlew bootrun
保存基础产品
curl --location 'http://localhost:8080/api/v1/products' \
--header 'content-type: application/json' \
--data '{
"productid": 101,
"name": "apple iphone 16",
"model": "iphone 16",
"color": "black",
"storage": 128,
"warranty": 1,
"price": 12.5
}'
保存变体
curl --location 'http://localhost:8080/api/v1/products/101/variants' \
--header 'Content-Type: application/json' \
--data '{
"model": "Iphone 16",
"color": "dark night",
"storage": 256,
"warranty": 1,
"price": 14.5
}'
结果(新变体仍然存在,没有任何问题)

您可以在以下 github 存储库中找到产品变体的原型设计模式的完整实现:
github 存储库链接
保持联系并关注我,获取有关软件开发、设计模式和 spring boot 的更多文章、教程和见解:
在 linkedin 上关注我
原型设计模式是一个强大的工具,适用于对象重复频繁的情况,如电子商务应用程序中的产品变体。通过在 spring boot 应用程序中实现此模式,我们提高了对象创建的效率和代码的可维护性。这种方法在需要创建具有较小变化的相似对象的场景中特别有用,使其成为现实应用程序开发的一种有价值的技术。
以上就是在 Spring Boot 中实现原型设计模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号