Home >Java >javaTutorial >Implementing the Prototype Design Pattern in Spring Boot
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.
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.
Reduces Initialization Time: Instead of creating objects from scratch, you clone and modify existing instances, saving on initialization time.
Encapsulates Object Creation Logic: You define how objects are cloned within the object itself, keeping instantiation details hidden.
Enhances Performance: For applications that frequently create similar objects, such as product variants, the Prototype Pattern can improve performance.
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.
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.
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.
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)); } }
Here:
saveVariant: This endpoint handles HTTP POST requests to create a variant for a specified product. It delegates the creation logic to ProductService.
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.
./gradlew build ./gradlew bootRun
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)
You can find the full implementation of the Prototype Design Pattern for product variants in the following GitHub repository:
GitHub Repository Link
Stay connected and follow me for more articles, tutorials, and insights on software development, design patterns, and Spring Boot:
Follow me on LinkedIn
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!