search
HomeJavajavaTutorialImplementing the Prototype Design Pattern in Spring Boot

Introduction

In application development, managing object creation can be complex, particularly when dealing with instances that are almost identical but vary in specific details. The Prototype Design Pattern offers a solution by allowing us to create new objects by copying, or “cloning,” existing ones. This pattern is especially useful when objects are expensive to create or involve extensive initialization.

In this article, we’ll explore how to implement the Prototype Design Pattern in a Spring Boot application, using a practical e-commerce use case: creating and persisting product variants. Through this example, you’ll learn not only the fundamentals of the Prototype Pattern but also how it can streamline object creation in real-world applications.

Understanding the Prototype Design Pattern

The Prototype Pattern is a creational design pattern that allows you to create new instances by cloning an existing object, known as the prototype. This approach is particularly useful when you have a base object with various properties, and creating each variant from scratch would be redundant and inefficient.

In Java, this pattern is often implemented using the Cloneable interface or by defining a custom clone method. The main idea is to provide a “blueprint” that can be replicated with modifications, keeping the original object intact.

Key Benefits of the Prototype Pattern:

  1. Reduces Initialization Time: Instead of creating objects from scratch, you clone and modify existing instances, saving on initialization time.

  2. Encapsulates Object Creation Logic: You define how objects are cloned within the object itself, keeping instantiation details hidden.

  3. Enhances Performance: For applications that frequently create similar objects, such as product variants, the Prototype Pattern can improve performance.

E-commerce Use Case: Managing Product Variants

Imagine an e-commerce platform where a base product has various configurations or “variants” — for instance, a smartphone with different colors, storage options, and warranty terms. Rather than recreating each variant from scratch, we can clone a base product and then adjust specific fields as needed. This way, the shared attributes stay consistent, and we only modify the variant-specific details.

In our example, we’ll build a simple Spring Boot service to create and persist product variants using the Prototype Pattern.

Implementing the Prototype Pattern in Spring Boot

Step 1: Defining the Base Product

Start by defining a Product class with the necessary fields for a product, like id, name, color, model, storage, warranty, and price. We’ll also add a cloneProduct method for creating a copy of a product.

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

In this setup:

cloneProduct: This method creates a clone of the Product object, setting the ID to null to ensure that the database assigns a new ID for each cloned instance.

Step 2: Creating a Service to Handle Variants

Next, create a ProductService with a method to save variant. This method clones a base product and applies the variant-specific attributes, then saves it as a new product.

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);
    }
}

In this service:

saveVariant: This method retrieves the base product by ID, clones it, applies the variant’s details, and saves it as a new entry in the database.

Step 3: Controller for Creating Variants

Create a simple REST controller to expose the variant creation 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));
    }
}
</product></product>

Here:

saveVariant: This endpoint handles HTTP POST requests to create a variant for a specified product. It delegates the creation logic to ProductService.

Benefits of Using the Prototype Pattern

With this implementation, we see several clear advantages:

Code Reusability: By encapsulating cloning logic in the Product class, we avoid code duplication in our service and controller layers.

Simplified Maintenance: The Prototype Pattern centralizes the cloning logic, making it easier to manage changes to the object structure.

Efficient Variant Creation: Each new variant is a clone of the base product, reducing redundant data entry and ensuring consistency across shared attributes.

Run the program

Build the Spring Boot project using Gradle

./gradlew build
./gradlew bootRun

Execute via Rest client

Save base product

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

Save variants

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

Result (New variant persisted without any issue)

Implementing the Prototype Design Pattern in Spring Boot

GitHub Repository

You can find the full implementation of the Prototype Design Pattern for product variants in the following GitHub repository:

GitHub Repository Link

Follow Me on LinkedIn

Stay connected and follow me for more articles, tutorials, and insights on software development, design patterns, and Spring Boot:

Follow me on LinkedIn

Conclusion

The Prototype Design Pattern is a powerful tool for cases where object duplication is frequent, as seen with product variants in e-commerce applications. By implementing this pattern in a Spring Boot application, we improve both the efficiency of object creation and the maintainability of our code. This approach is particularly useful in scenarios that demand the creation of similar objects with small variations, making it a valuable technique for real-world application development.

The above is the detailed content of Implementing the Prototype Design Pattern in Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software