Builder Design Pattern
HTML-код
- Опубликовано: 7 фев 2025
- Get the Code: goo.gl/aR6AW
Best Design Patterns Book : goo.gl/W0wyie
Welcome to my Builder design pattern tutorial. You use the builder design pattern when you want to have many classes help in the creation of an object. By having different classes build the object you can then easily create many different types of objects without being forced to rewrite code.
The Builder pattern provides a different way to make complex objects like you'd make using the Abstract Factory design pattern.
Thank you :) I do my best. Most people don't make tutorials on obscure topics like this because they are almost guaranteed to not get views. I guess by not making videos just for views I fill a niche. I'm glad you like them
that makes you special Derek. Many Thanks
I literally pay thousands of dollars to learn this in class, yet the best teacher is right here teaching it for free! God bless you!
Thank you for the compliment :) I'm happy to be able to help. May God bless you as well!
I'll be covering c & c++ when I get into graphics programming. The plan is to teach you everything a software engineer knows. The oop principles I'm teaching directly translate to programming in c++. I wanted to turn this Java tutorial into an all encompassing software engineering course. I don't think anyone has ever done that online? I want to make you into an expert rather than a mere hacker :)
11 years on and the legacy continues...terrific terrific terrific
You are my design patterns learning source, I always start constructing from the background that your videos provide me. Thanks!
Hello Derek,
First of all I want to thank you for all your videos and tutorials that helped me a lot during my java career, I think though that this video needs to be updated because it does not represent, afaik, the real builder pattern, a very simple example of the builder patter is Java's StringBuilder if you see how a string is made from a stringBuilder you'll notice that there is a big difference between how you instantiate your Robot object and how we instantiate the String from the builder:
StringBuilder builder = new StringBuilder();
String s = builder.append(....).append(....).append(.....).append(...).toString(); //This is how a builder should return an object by calling different methods and returning the object once we call the build method. (the build method is often called build())
I think what you did here is more of a Factory . Please review and give me a feedback if you agree.
Regards
In my refactoring tutorial I show that builders often build composites (trees). Factories are less complicated, but more customizable. Builders are more complex and also more flexible. The most common thing about Builders is that they make objects step-by-step, while factories create everything all at once. I hope that helps
"Wololo, internet and welcome to part 8..."
This gave me a good chuckle.
I hn hn..
Something that I didn't state enough in this series is that the design patterns are a guide and not necessarily set in stone rules. They are flexible and this is probably why the gof book has been around for so long. They state this in the book, but I don't have it on hand at the moment. I could have actually made many videos for each pattern, but I instead decided to demonstrate the flexibility in just 2 of the patterns. This was one of those. I hope that makes sense?
One of the nice things about youtube is being able to watch these at 1.5 or 2x speed to be able to quickly review.
soozler That is a lot to take in at 2x speed. I'm glad I could help :)
I think you are missing the very own intention of the builder pattern which is to create the complex object having many attributes which could be set in any order.
Yes the build methods should really take parameters. That way the build process would allow different types of robots
The basic intention of the pattern is to separate the construction of a complex object from its representation. So the construction is defined via the interface ie. RobotBuilder which defines the construction and the various implementations of this interface would be the different representations of the Robot, he mentions this at 6:30
@@josephfernando4867 no, it is a Factory what you are talking about (and the video too, just with the Builder "syntax"), a Builder makes sense if you have a constructor that takes too many parameters, for example if you have a Robot constructor with 5 Strings or more, you have to go to the implementation and look the parameters order to instantiate it correctly.
The idea of the Builder pattern is to set the parameters via methods with an explicit name and that is it, and nothing else...
@@cesardmora86 Factory pattern is used to instantiate an object of a certain form and return it to the client. That is a simpler pattern, where just one method of the factory returns an instance required by client.
In case of Builder pattern there are several steps in constructing the object. As shown in the example, buildRobotHead, buildRobotTorso etc. In this example the way to construct the robot is encapsulated in the robotbuilder interface and the RobotEngineer does not need to know how it is being constructed, ie. the definition of the builder pattern which is to hide the construction process from the client, which is the same as factory pattern but only difference being in this case it is more complicated, there are several steps involved in building the object.
Now the second part of the definition of builder is to separate construction from the actual representation and that is being done here. The Construction process is defined in the RobotBuilder interface and the actual representation of the process is in the OldRobotBuilder class
Here a video on java
ruclips.net/video/0GTe8e7DYHk/видео.html
Some times I put them on my site. I link to the articles in the description. For this specific video I didn't show the diagrams for some reason. Sorry about that
I made another tutorial on the abstract factory pattern. Check out the last part of my refactoring tutorial. It should help
Thank you for making the video. 2 humble suggestions:
Imho engineer.makeRobot() should return a robot instead of engineer.getRobot. I would remove the method engineer.getRobot since it will throw exceptions if someone doesn't call makeRobot first. Let the engineer just createRobots and not store them so nobody has to worry about what state the insides of the engineer are in.
I would also make the Robot's constructor private so developers using your "Robot ToolBox" are forced to go through the builder or engineer since that is where you are enforcing your rules. It would also further stress the reasons your using the builder.
Humble suggestions, thanks for putting these videos together.
Been trying to learn patterns. I like this builder but setting robot constructor to private will cause an error on OldBuilder class. Any idea how to deal with this?
"Let the engineer just createRobots and not store them so nobody has to worry about what state the insides of the engineer are in."
The problem with this is that instead of the robotBuilder instance in RobotEngineer class,we will then need an OldRobot instance or need a new OldRobotBuilder() created in makeRobot() method which defeats the purpose of the builder pattern. ( If ever we need to chang the blueprint of the robot all we have to do is swap the OldRobotBuilder class with a new one and we are set. By your approach we will also then need to modify lines of code in the RobotEngineer class.
You found the only other pattern that I changed, with proxy! You are definitely understanding the patterns if you caught both. I should have better explained why I made the changes that I did. I'm glad you understood my logic. I'll do my best with the android tutorial. It is going to be very long
Best Think about your videos is "They are not boring!!!"
I watched many of your videos in the last few days. What you are doing is so amazing. I have read the good old GoF few times before. Although I get what the book is saying, the examples you give and the way that you explain it makes it very easy to relate to. This is really interesting stuff here and very rare. Kudos to you. Thank you very much for your efforts.
Yeah that makes 100% sense. Thanks! Iv'e watched almost all your design pattern videos and the proxy pattern was the only other one that didn't correlate directly. The proxy pattern video only shows the use in a security sense when there are 4 different variations in GOF. But your right as stated in the book and by my engineering of software sub-systems class professor all patterns are simply guides. Keep up the awesome work btw! I plan to continue to watch your android development series.
Derek Banas you must be a super hero.....super speed..making things better every time....thanks for another excellent video. :-D
That is very nice of you to say that. I do my best to make learning all of this stuff fun :) I think programming and electronics can turn all of us into super heroes.
Speed is the only answer I can give. Yes you need Java installed to run Java apps, but those apps run on every os. A Windows exe for example won't run on a Mac without recompiling or changing the code. I mainly use Java with C to get the best of both worlds. If you were just aiming to make desktop apps I'd say go learn C++, but in the tablet world in which we live Java is king in my opinion. You can also convert Java to Obj C to run on iOS
I got a habit of "Liking" your video before even watching it . Cheers!!! :-)
Java is probably a second tier language in regards to complexity. I'd consider Python to be the easiest language, but languages like c and c++ are more complicated than Java because you have to handle memory management largely on your own. If you learn Java, you'll find c++ is pretty easy because you'll have the oop stuff under your belt. C# is extremely similar to Java. I'll cover c / c++ when I'm done with Java and when I need them to handle graphics for making Android apps
I apreciate your answer! But...I think you replied to wrong person. I was pointing that you don't have to learn C++ if you already know Java (except you want to make complex 3D games where the speed is crucial factor) And Java isn't so slow as they are talking about, in most cases its faster than C#, and about 0.20 - 25 times slower than C++ :)
The builder pattern is much less complicated then most factory patterns. There are other great reasons for using the different patterns based on how well they match up to the real world objects they represent. Have you see my Object Oriented Design and Refactoring tutorials. I go into detail on these topics there
Thanks Derek, Now I understand, how exactly the QueryBuilder and others objects works when I was working with technologies like Elastic search and others for querying
I'm happy it helped :)
Thank you :) I don't know how I attracted so many nice people to my community
I think you made the Factory pattern just with the Builder "syntax".
A Builder makes sense if you have a constructor that takes too many parameters, for example if you have a Robot constructor with 5 Strings or more, you have to go to the implementation and look the parameters order to instantiate it correctly.
The idea of the Builder pattern is to set them via methods with an explicit name for each parameter, and that is it, and nothing else... it's not more complicated than that.
Another "problem" in this video is that the getRobot method returns always the same instance. So you could do:
engineer.makeRobot();
firstRobot = engineer.getRobot();
engineer.makeRobot();
secondRobot = engineer.getRobot();
assert firstRobot != secondRobot;
and then expect 2 different instances, but it is not.
The build method of a Builder should return always a different instance: this is convention.
He incorporated the Factory Pattern to build a family of Builder objects. It's neat that he has done that, considering that he showed Factory Pattern on a previous video. However, it is confusing to a person just learning about patterns. Someone with little experience will think that in order to use the Builder pattern, you must use it in conjunction with a Factory; which is not the case.
@@professorfontanez That's why I always start by reading comments before watching the video ^^
Hats Off Boss !!!! You keep us afloat.
RobotPlan isn't really needed for this pattern. I just used it because I like using interfaces and technically I could have and should have used it more in the code. It isn't a part of the pattern though
I don't check Facebook. I'm very active here and on google+ though. Facebook blocks my RUclips videos, so I pretty much stopped using it
Thanks for for bringing all design patterns in form of video. You explained very well with sophisticated examples. I like the way you explain thanks...
Thank you very much :)
I think it would be really interesting to make another implementation of robotBuilder like NewRobotBuilder to show people
how it's flexible to create many types of robots by switching from an implementation to another, since you just have to set the new RobotBuilder inside the RobotEngineer.
This will help me a lot with the library i'm trying to make in java!
Thank you so much!
You're very welcome :)
You're very welcome :) I'm glad to have been a help
MVC is coming! Thank you :)
Thank you very much :) I thought the gof book was hard to understand when I first saw it as well. I'm very happy if I've made more sense of the topic because I think it is very important
It's ok, I was to involved on the material that I missed to be more specific.
It's just that you defined the RobotPlan interface at 2:21 containing the definitions for methods a robot must have (only set methods) but I didn't see when this restriction was playing a part, since it was used Robot class for the OldRobotBuilder class as it is defined on its implemented RobotBuilder interface. Why to define a RobotPlan interface when we are using Robot class with getters and setters?
Nice coding eg but can you explain how is it going to make a difference b/w this and factory desgin pattern because in factory pretty the same happens?
I'm very happy to help :)
You're saving my life man. Maybe I'll do my project now ;) Thank you!
I'm very happy I could help :)
Got it finnally after 3
months
Thank you for all of your videos so far. By looking at this particular video it does not look very much like the builder pattern explained in Joshua Bloch's effective Java. In my humble opinion this looks like a hybrid of a factory method that incorporates the command design pattern. Please correct me If I am wrong as my aim with this comment is to develope a much stronger understanding and learning from guys like you.
You're very welcome :) Yes I did my best to explain at the beginning of the video that there is much disagreement about the builder pattern. Many people believe it has one form, but I have decided that many respected programmers have described it in many ways which to me means that it has many forms. I consider something to be a builder if you have many classes help in the creation of an object and it is done in a way that is different from the different flavors of factory patterns. I hope that clears that up.
Thanks Derek for such a nice explanation ! But i have a small query -
0:53 "Whenever you create a builder pattern, the builder part of the pattern knows all the specifics and every other class involved knows nothing about what's going on in regards to the specifics of the final object that you are gonna create" - However, if our old school robot gets a tail - not only our builder will change, but our engineer will also change. Or what if we decide to add a new type of robot - then either we'll need to make lots of changes to our Engineer class or create a new Engineer class. Is this a shortcoming of the builder pattern ? Patterns should help solve these design problems, but the problem seems to snowball here. I am confused, please help !
because it is the crux part of the pattern - the place for implementation though client aka main class doesnt directly accessing Robot
Hope it helps!
Joshua Bloch's Builder pattern is not the same as the original (and best in my opinion) GoF Builder pattern. Derek's explanation is based on the GoF Builder pattern.
Also the engineer in Derek's explanation is the Director (GoF).
Thanks again to take your time and doing this free recalls mate!! Really appreciated
+Ewerton Silveira You're very welcome :)
I want to thank you really for the effort you do to lean us and really u r amazing in explain anything its a gift that so incredible
Thank you :) I apologize, but I'm not understanding your question. Sorry about that
Derek Bananas thanks for the video!
Thank you :) I'm happy I could help
Amazing explanation Derek!, a video is definitely a lot more helpful than the wikibooks
Cal Ferns Thank you for the compliment :)
What is the advantage to this over having different enums for different robot types?
Your videos are really amazing I really appreciate the info thank you🙂
Thanks for backing me up, but it doesn't bother me :)
Great tutorial, thank you very much. This helped my my software project for college look alot more tidy and professional!
Hi Derek,
I notice the the RobotEngineer it's coupled with the RobotBuilder, since the composition is set on the constructor. Every time the main needs a new kind of robot, it needs to create a new builder and a new engineer.
I guess I don't really understand why we need the Engineer, since it's not hiding the builder from the "user" nor is capable of calling different builders with the same Engineer instance..
Thanks a lot!
Gonza
Hi, I saw you answered a comment from 12 days ago, so I thought I'll take a shot. So if i understood correctly, if I wanted to create another style robot, i would have to create a class NewRobotBuilder implementing RobotBuilder interface and then just create RobotEngineer robotEngineer2 with newStyleRobot object in it?
I'm currently reading GOF and it states that the concrete builder itself should be returning the product not the director. In this example, the director is returning the product. Though the director is getting it directly from the builder and is simply passing it along. Not sure which is the correct way to use the builder pattern here.
Thank you :) You missed your chance to post first :D
This video is a bit old but I'm going to point it out anyway.
In your implementation you create a new Robot object only in a RobotBuilder's constructor and nowhere else. Because of that whenever I want to create a new Robot I need to create a new RobotBuilder object and preferably a RobotEngineer as well. Otherwise I would end up with multiple references to the same object.
To fix that we could create a new method createNewRobot() in the RobotBuilder class and call it in a makeRobot() method in the RobotEngineer.
Other solution would be calling a copy constructor in a getRobot() method in the RobotEngineer. ( return new Robot(this.robot);)
Thanks for your videos.
Amongalen I think that’s the point of a builder .. in situations where you have multiple parameters in a constructor all of the same type it’s important to be able to explicitly define what your parameters are without having to store them in variables with descriptive names i.e new object( “string”, “string”, “string”). His implication prevents a constructor with multiple string parameters. It also allows readable code.
I don't really see any connection between a constructor with multiple parameters and a problem pointed in my previous comment (returning reference to already existing object instead of creating a new one).
In my solution everything would be almost the same, just add OldRobotBuilder.createNewRobot() {this.robot = new Robot()} and call it in RobotEngineer.makeRobot() before any other method. And that's it, you got a new object every time you need it. Without the need to create a new RobotEngineer or RobotBuilder.
What is more, that's the way how it's implemented in other sources.
Amongalen I agreed, his current builder has a 1:1 relationship with robots ..
Thanks for this. Very useful.
Thank you very much :) I did my best
Derek, do you have a blog post or a video talking about how you got your first job in software development or if you went to college or not? Anything like that? Thanks alot! I am watching these patterns and then watching them be re implemented in C# and going from there. C# is my language. But I can understand Java, hence the C#.
You're are very welcome :) I did an ask me anything once in which I talk about that. I mainly got hired by Apple after winning a college science fair. I rewired Nintendo power gloves and made a head mounted display. Then I let people play video games with them. It was so popular that I had a line that wrapped around the entire building. It was pretty cool.
After that I was invited to take a test and Apple hired me. It was a very interesting time.
Oh ok awesome yes I will check out that video. Do you have any experience with Microsoft technologies, like the C# language or are you more mobile - platform oriented with Java and Native language?
Derek Pauley I know C#. It is very similar to Java. About the only thing I haven't used fairly regularly is asp.
Oh ok cool. Yes it is very close to Java with some differences in the way it handles generics and delegates. But my focus right now is the MS web stack .. ASP.NET MVC is awesome. I did research Spring MVC and do plan on doing some Java work in school and with your videos. I also watched a course on Ruby on Rails ... again very similar. They each just have a few differences to consider but other than that it seems that there is a tool for everyone.
I'm not sure what editor you use, but in notepad++ there's an option under "TextFX -- >TextFX Tools" to get rid of the numbers. I think there's something similar in NetBeans and Eclipse too :)
Hi Derek, I don't think this is the way to implement Builder pattern. Your OldRobotBuilder class can create only one type of Robot. What if Robot has a property "color", so in your implementation you need "RedOldRobotBuilder" and "BlackOldRobotBuilder" classes to create Red and Black robots. Your code is against the use of variables, because you have made it constant in the Builder class.
Yes but the problem with introducing parameters is that the client then has to be aware of them and specify them. Using a Pizza analogy, do you want the client to specify every ingredient for a margerita pizza and same for meatlovers pizza. In that scenario i.e. if we have Pizza builders it would be better to have multiple concrete pizza builders instead of a general pizza builder that takes parameters. You're point is still valid but it really depends on the scenario and how complex the object is. For very complex objects with lots of parameters it's probably better to use multiple concrete builders while for more simple scenarios a parameter approach might be better.
Pankaj Kumar I agree
Amazing videos, maybe ill have to re-watch it a couple times, because it seems overly complicated, this is like an anti DRY pattern, it feels like Please Repeat Yourself. I mean it seems really useful, but it adds a lot of complexity, is it really worth it? Compared to the factory, is this pattern used that much? Thanks for your hard work.
Felipe Roman You're very welcome :) Patterns are more like perfect solutions that are used on occasion rather then something we should try to force into an implementation. That is probably the hardest thing to learn. Yes this pattern is very useful when you want to create any different versions of similar objects.
Hey Derek, is this following example also a form of the builder pattern, or are there constraints that I'm neglecting? Here's my code:
```
// Robot.java
public class Robot {
private String head;
private String torso;
private String arms;
private String legs;
public Robot setHead(String value) {
head = value;
return this;
}
public Robot setTorso(String value) {
head = value;
return this;
}
public Robot setArms(String value) {
head = value;
return this;
}
public Robot setLegs(String value) {
head = value;
return this;
}
}
// Builders.java (wishing stand-alone functions also existed in Java, but psuedo-namespaced classes it is)
public static class Builders {
public static Robot Old() {
return new Robot()
.setHead("Tin Head")
.setTorso("Tin Torso")
.setArms("Tin Arms")
.setLegs("Tin Legs")
}
public static Robot Latest() {
return new Robot()
.setHead("Titanium Head")
.setTorso("Titanium Torso")
.setArms("Titanium Arms")
.setLegs("Titanium Legs")
}
}
```
What is the main difference between the factory class and the builder class? It kinda does the same thing right?
The factory patterns are more concerned with creating simple objects while the builder pattern is concerned with building complex objects
As someone mentions above, Dereks explanation doesn't really highlight the fact that the Builders can take parameters. He's simplified it. If the setters took parameters then the builders can build different robots depending on the parameters they receive. It's also possible to create new builders i.e. you could have a fastrobotbuilder or Bigrobotbuilder however that, obvioulsy, requires creating a new concrete builder.
Thank you so much for this great tutorial
+Mohammed Hashim You're very welcome :)
I currently finish Abstract Factory Pattern, but I am confused by the relationship between them. What's the difference between Builder pattern and Abstract Factory pattern?
Would the builder pattern be the correct choice for an Order Calculator that subtotals products purchased, total tax and total purchase amount/
Where can I get the diagrams you use to show the scheme/layout of these designs? They are extremely helpful.
What is the difference in Builder pattern and Abstract Factory pattern? Fundamentally, both seem to abstract the type of factory/builder and use composition to create objects with dynamically setting their attributes/parts.
The Builder is used when an object must be created in a series of steps.
What if I don't want to predetermine what kind of parts a robot consists of? for example the user may build a robot without a right arm, maybe add a weapon or a tool, or add extra components to the head.
Your efforts are much appreciated, but can you try modulating your voice a bit, i am finding it difficult to comprehend.
Sorry about that. I'm constantly trying to improve the videos. Thanks for the input
I didn't get the need for creating a RobotBuilder or Engineer as we can directly create a Robot instance and set the properties. How does creating a builder or engineer help? The example is more about delegation rather than the builder pattern. My understanding of Builder says that it is used in places where we need to pass a lot of parameters in the constructor while creating a model.
The coding style and presentation is very good for these videos. However, they do not make up for the poor/inconsistent naming that is chosen. This has made the concepts more unnecessarily confusing in multiple videos now. I hope that you have improved on your naming conventions over the years, because it is really holding you back at this point.
Example:
robotBuilder oldStyleRobot
Why is a builder type being named as if it were an actual robot? And for that matter, how is an outsider supposed to know what the difference is between a "builder" and an "engineer"? You clarify at this point that the builder is a blueprint for the engineer, which makes sense. So why is the type or at least the name not a blueprint instead?
Great explanation
Thank you :)
Hi, Derek
On what part is where the RobotPlan interface comes into play?
I love your vids.
Please cover the Model-View-Controller design pattern, and keep up the great work
Nice videos. Thanks a lot
Iyyappan N Thank you :) You're very welcome
Nice explanation
we can create a class "OldRobot" and "SpaceRobot" by implementing a Robot Interface. set all the values in their constructor. now we can apply the factory method pattern for these two robots. Why we need Builder design pattern?
In this example, how it is different from Strategy Pattern. RobotEngineer can be a strategy, and OldRobotBuilder is our required strategy which we pass to RobotEngineer constructor.
Yes, You are right .. The implementation is implementation of Strategy Pattern.
Strategy1 - OldRobotBuilder and Strategy2 - RobotBuilder and that the RobotEngineer Chooses the type of strategy to apply.
The implementation needs a revisit.
Builder provides the Client flexibility to set only required capabilities as per client need and return the Object based on the same.
example
Person tom = new Person(Name,DOB, X,Y,Z,null,null,abc);
Using Builder
PersonBuilder personbuilder = PersonBuilder.getBuilder();
personbuilder .add(name).add(DOB).add(salary);
Person tom = personbuilder .build();
Here you have RobotEngineer knowing about the concrete Robot class. Wouldn't it be better to code to the interface and have it return a RobotPlan? RobotPlan would then need the getter methods as well. By the way, reading and loving the book you recommended.
JR Roberts Yes that is a nice design. I tried to simplify the code above all else. I'm glad you like the book.
Hi +Derek Banas
In my opinion, Abstract Factory design pattern uses the concept of Builder design pattern to build the diffrerent factory, doesn't it?
+Lester Abstract Factory design pattern is for creating objects with fixed configuration whereas Builder is to create objects with customized configuration.
When I try to create a customized object using Factory design pattern, I could clearly understand the difference between factory and builder patterns. Hope this helps.
It looks like abstract factory pattern ! Can you tell me what's the difference in short? :D thx
Cailin Liu Builders build complex objects step-by-step. Factories build families of similar objects
I love your videos, just one tiny thing, can you just slow down a little bit when you talk? Thanks.
I'm doing my best to always improve my speed. Thank you for the input.
***** Thank you :) I figured that since every other tutorial person is making very slow videos that it would be a good idea to be different and make fast ones. I'm glad you enjoy them.
Dude, you are awesome. Subscribed.
Jason Lough Thank you very much :)
You rock, seriously!
Thank you :) I try to do my best
Hi, Why not set the get methods of the robot class in the robotplan interface?
I keep coming back to your videos to lear and/or reference the various design patterns. Do you think you can perhaps implement the examples using python? Thanks.
+Zile Rehman Thank you :) I have been working on covering design patterns using multiple languages. I'll do my best.
I have added a few in python after following your tutorial. You can use it as a reference or feel free to copy and paste as needed. It's for a good cause...
github.com/rehmanz/python-algorithms/tree/master/design_patterns
Thanks for the clear and concise videos on a challenging subject. Could you give an example of a business application of this pattern?
Here you should not create makeRobot() method in the RobotEngineer class, it is breaking flexibility achieve object creation as per needed parts. If user wants to create a robot without hands or arms, flexibility is not there to do so. Although you could use static inner class in this to achieve this.
Thank you very much :)
is it possible to have multiple builders? if so, how would look like?
I just realized that if you hit View Source you can directly copy and paste, omg ily
Hi Derek - this is fantastic, but I had one question in OldRobotBuilder you didn't use the "this" operator while assigning values but you used it in getRobot() - this is something that I didnt understand. I thought one should always use when using instance variables inside a class. I shall await your reply and once again - thank you for the tutorials.
+Prasenjit Giri there instance variable name is not clashing withe name of the constructor parameter.so it should be cool i believe
Thank you :)
I don't think the robot implementation here is a good example because the robot merely consists of 4 primitive type fields. The purpose of the builder pattern is to build complex objects composed of other objects without knowing about their implementation. You should add some more objects inside of the Robot class.
awesome job.. thank you
Thank you :)
If there is much more logic in creating a robot (like needing to access satelites and nation army fabrics) should i put the additional logic in builder, engineer or separate class?
+Danon W From my understanding, the functionality you mentioned handles by structural patterns not by creational.
If the question is, how to add one more part to Robot like antenna, please find the below steps
1. add a member function to RobotBuilder like buildRobotAntenna() and do the actual implemention in oldRobotBuilder like other build functions
2. add a member function to RobotPlan like setRobotAntenna() and do the actual implemention in Robot
3. update makeRobot() member function in RobotEngineer to call buildRobotAntenna() on RobotBuilder like other calls
Hope this answers your question.
The world has 270.222 people who like coding. We are few and privileged.
I'm learning builder patterns but I learned them in a different way! I thought the point of a builder pattern was to construct the same class object but with different attributes / fields. Say your robot has more attributes such as color, wifi enable, UV vision.. and so on. With your example we would have to create different class objects and different parameters or, as you do it, a different makeRobot() for every robot class. For the builder pattern don't you want to create a public static class Builder in Robot and thus construct a new one as new Robot.Builder().arms("Wood stack").torso("Metal Armor") and so on?
Yes, You are right Bruno, I think he is missing that point
I think he was trying to keep it simple, with this base implementation I’m sure you could parametrize the builder but you would need to either remove the engineer or rework the engineer
I'm assuming the buildHead, buildTorso, buildArms, and buildLegs methods should be private..
Only the makeRobot should be public in RobotEngineer class, correct ?, if so how to use polymorphism with Interfaces of properties that are private but only one method makes them publically accessible ?