在 Spring Boot 中实现原型设计模式

介绍

在应用程序开发中,管理对象创建可能很复杂,特别是在处理几乎相同但具体细节有所不同的实例时。原型设计模式提供了一种解决方案,允许我们通过复制或“克隆”现有对象来创建新对象。当对象的创建成本高昂或涉及大量初始化时,此模式特别有用。

在本文中,我们将使用实际的电子商务用例来探索如何在 spring boot 应用程序中实现原型设计模式:创建和保留产品变体。通过这个示例,您不仅可以了解原型模式的基础知识,还可以了解它如何简化实际应用程序中的对象创建。

了解原型设计模式

原型模式是一种创建型设计模式,允许您通过克隆现有对象(称为原型)来创建新实例。当您拥有具有各种属性的基础对象时,这种方法特别有用,并且从头开始创建每个变体将是多余且低效的。

在 java 中,这种模式通常使用 cloneable 接口或定义自定义克隆方法来实现。主要思想是提供一个可以通过修改进行复制的“蓝图”,保持原始对象完整。

原型模式的主要优点:

减少初始化时间:您无需从头开始创建对象,而是克隆和修改现有实例,从而节省初始化时间。

封装对象创建逻辑:您可以定义如何在对象本身内克隆对象,同时隐藏实例化详细信息。

增强性能:对于经常创建类似对象(例如产品变体)的应用程序,原型模式可以提高性能。

电子商务用例:管理产品变体

想象一个电子商务平台,其中基本产品具有各种配置或“变体” – 例如,具有不同颜色、存储选项和保修条款的智能手机。我们可以克隆基础产品,然后根据需要调整特定字段,而不是从头开始重新创建每个变体。这样,共享属性保持一致,我们只修改特定于变体的细节。

在我们的示例中,我们将构建一个简单的 spring boot 服务,以使用原型模式创建和保存产品变体。

在 spring boot 中实现原型模式

第 1 步:定义基础产品

首先定义一个产品类,其中包含产品的必要字段,例如 id、名称、颜色、型号、存储、保修和价格。我们还将添加一个 cloneproduct 方法来创建产品的副本。

public interface productprototype extends cloneable {    productprototype cloneproduct();}

登录后复制

@entity@table(name = "products")@datapublic 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。

第 2 步:创建处理变体的服务

接下来,创建一个具有保存变体方法的 productservice。此方法克隆基础产品并应用特定于变体的属性,然后将其另存为新产品。

public interface productservice {    // for saving the base product    product savebaseproduct(product product);    // for saving the variants    product savevariant(long baseproductid, variantrequest variant);}

登录后复制

@log4j2@servicepublic 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 检索基本产品,克隆它,应用变体的详细信息,并将其保存为数据库中的新条目。

第 3 步:创建变体的控制器

创建一个简单的 rest 控制器来公开变体创建 api。

@restcontroller@requestmapping("/api/v1/products")@log4j2public class productcontroller {    private final productservice productservice;    public productcontroller(productservice productservice) {        this.productservice = productservice;    }    @postmapping    public responseentity 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 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));    }}

登录后复制

这里:

savevariant: 此端点处理 http post 请求以创建指定产品的变体。它将创建逻辑委托给 productservice。

使用原型模式的好处

通过此实施,我们看到了几个明显的优势:

代码可重用性:通过将克隆逻辑封装在 product 类中,我们避免了服务和控制器层中的代码重复。

简化维护:原型模式集中了克隆逻辑,可以更轻松地管理对象结构的更改。

高效变体创建:每个新变体都是基础产品的克隆,减少冗余数据输入并确保共享属性的一致性。

运行程序

使用 gradle 构建 spring boot 项目

./gradlew build./gradlew bootrun

登录后复制

通过rest客户端执行

保存基础产品

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}'

登录后复制

结果(新变体仍然存在,没有任何问题)

在 Spring Boot 中实现原型设计模式

github 存储库

您可以在以下 github 存储库中找到产品变体的原型设计模式的完整实现:​​

github 存储库链接

在 linkedin 上关注我

保持联系并关注我,获取有关软件开发、设计模式和 spring boot 的更多文章、教程和见解:

在 linkedin 上关注我

结论

原型设计模式是一个强大的工具,适用于对象重复频繁的情况,如电子商务应用程序中的产品变体。通过在 spring boot 应用程序中实现此模式,我们提高了对象创建的效率和代码的可维护性。这种方法在需要创建具有较小变化的相似对象的场景中特别有用,使其成为现实应用程序开发的一种有价值的技术。

以上就是在 Spring Boot 中实现原型设计模式的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2608507.html

(0)
上一篇 2025年3月6日 20:39:52
下一篇 2025年2月22日 20:04:38

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论