From the course: Complete Guide to Java Design Patterns: Creational, Behavioral, and Structural
Unlock this course with a free trial
Join today to access over 25,300 courses taught by industry experts.
Solution: The Builder pattern - Java Tutorial
From the course: Complete Guide to Java Design Patterns: Creational, Behavioral, and Structural
Solution: The Builder pattern
Let's have a look at my solution to this builder pattern exercise. If you've done yours slightly differently, that's totally fine. So the first thing I've done is inside the StoreItem class, I've created a new static class called StoreItemBuilder, and this has all the same fields as a StoreItem. And inside the constructor, I'm passing in a name and a price, and I'm making sure that neither of those are null. And then I have methods for setting all of the optional fields. So, for example, I have a method called shortDescription which takes a string and sets the shortDescription fields to that string that's passed in. And this returns a StoreItemBuilder object. And I have one of these for each of these optional fields. And then finally, I have a build method where I'm creating a new StoreItem and I'm passing in a StoreBuilder. So the constructor for the StoreItem has also changed, so if I go back up to the top. So instead of passing in all those different fields, this is now a private…