<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: pal murugan</title>
    <description>The latest articles on DEV Community by pal murugan (@palmuruganc).</description>
    <link>https://dev.to/palmuruganc</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1733230%2F38113d10-3351-4185-9dce-c17632da6767.jpg</url>
      <title>DEV Community: pal murugan</title>
      <link>https://dev.to/palmuruganc</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/palmuruganc"/>
    <language>en</language>
    <item>
      <title>Implementing the Prototype Design Pattern in Spring Boot</title>
      <dc:creator>pal murugan</dc:creator>
      <pubDate>Thu, 14 Nov 2024 16:29:01 +0000</pubDate>
      <link>https://dev.to/palmuruganc/implementing-the-prototype-design-pattern-in-spring-boot-4b4d</link>
      <guid>https://dev.to/palmuruganc/implementing-the-prototype-design-pattern-in-spring-boot-4b4d</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Understanding the Prototype Design Pattern
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Benefits of the Prototype Pattern:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Reduces Initialization Time: Instead of creating objects from scratch, you clone and modify existing instances, saving on initialization time.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Encapsulates Object Creation Logic: You define how objects are cloned within the object itself, keeping instantiation details hidden.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enhances Performance: For applications that frequently create similar objects, such as product variants, the Prototype Pattern can improve performance.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  E-commerce Use Case: Managing Product Variants
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

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

&lt;h2&gt;
  
  
  Implementing the Prototype Pattern in Spring Boot
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Step 1: Defining the Base Product
&lt;/h3&gt;

&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ProductPrototype extends Cloneable {
    ProductPrototype cloneProduct();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@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;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this setup:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;cloneProduct:&lt;/strong&gt; 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.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2: Creating a Service to Handle Variants
&lt;/h3&gt;

&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface ProductService {

    // For saving the base product
    Product saveBaseProduct(Product product);

    // For saving the variants
    Product saveVariant(Long baseProductId, VariantRequest variant);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@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(() -&amp;gt; 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);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this service:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;saveVariant:&lt;/strong&gt; 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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 3: Controller for Creating Variants
&lt;/h2&gt;

&lt;p&gt;Create a simple REST controller to expose the variant creation API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@RestController
@RequestMapping("/api/v1/products")
@Log4j2
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @PostMapping
    public ResponseEntity&amp;lt;Product&amp;gt; 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&amp;lt;Product&amp;gt; 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));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;saveVariant:&lt;/strong&gt; This endpoint handles HTTP POST requests to create a variant for a specified product. It delegates the creation logic to ProductService.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Using the Prototype Pattern
&lt;/h2&gt;

&lt;p&gt;With this implementation, we see several clear advantages:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code Reusability:&lt;/strong&gt; By encapsulating cloning logic in the Product class, we avoid code duplication in our service and controller layers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Simplified Maintenance:&lt;/strong&gt; The Prototype Pattern centralizes the cloning logic, making it easier to manage changes to the object structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Efficient Variant Creation:&lt;/strong&gt; Each new variant is a clone of the base product, reducing redundant data entry and ensuring consistency across shared attributes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Run the program
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Build the Spring Boot project using Gradle
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./gradlew build
./gradlew bootRun
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Execute via Rest client
&lt;/h4&gt;

&lt;p&gt;Save base product&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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
}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Save variants&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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
}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result (New variant persisted without any issue)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe1pjg0ooze6ddz9gua9x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe1pjg0ooze6ddz9gua9x.png" alt="Image description" width="800" height="117"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  GitHub Repository
&lt;/h3&gt;

&lt;p&gt;You can find the full implementation of the Prototype Design Pattern for product variants in the following GitHub repository:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/palmurugan/design-patterns/tree/main/prototype-pattern" rel="noopener noreferrer"&gt;GitHub Repository Link&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Follow Me on LinkedIn
&lt;/h3&gt;

&lt;p&gt;Stay connected and follow me for more articles, tutorials, and insights on software development, design patterns, and Spring Boot:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.linkedin.com/in/palmurugan-c-5b622573/" rel="noopener noreferrer"&gt;Follow me on LinkedIn&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>designpatterns</category>
      <category>coding</category>
      <category>java</category>
    </item>
  </channel>
</rss>
