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
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.
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
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 :)
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?
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
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.
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
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.
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
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.
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
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 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.
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.
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
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
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 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++ :)
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
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 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 !
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.
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.
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();
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.
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?
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.
The Engineer decouples the client from the Builder. The job of the Builder is to build the complex object. It's better that the builder it since the alternative is that the client do it.
Imagine a factory with no engineer or no director. Imagine a Tesla Inc. factory with all those automated machines without Musk and team to assemble different parts. Different parts of the factory / or even different factories manufacture different parts with different specs The engineer assembles then. I think the key thing is the builder vs the assembler. The Concrete Robot Builder assembles all the right manufactured parts
+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.
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
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.
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?
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.
Hello! If I need to create a new kind of robot, what should i do? for example, this new robot had head, no arms , torso and three legs. How can i make this? Should I create a new class of robot who implements RobotBuilder? Or may the director(robotEngineer) can do this? I'm confusse
When you inject the RobotBuilder into the RobotEngineer, you are forcing that instance of the RobotEngineer to only make that one kind of the Robot. Why can't you instantiate your engineer without passing it a plan, and then pass the RobotBuilder to the makeRobot() method of the engineer? This way, you can use the same engineer to create multiple different types of robots. Why would you choose the former (mentioned in your video) method?
+Kousha Talebian But in this implementation the makeRobot method is specifically calling the build methods of the builder that got passed. You would have to know the methods of the builder you get passed later on. That is not possible. The coupling to the builder needs to exist, anyway. So you create it right at construction time. Or you go one step further and let the makeRobot method only delegate to the makeRobot method inside the builder which then calls all its own methods. If you want to build more or less, then you need a different builder.
Actually it is possible since the concrete builder is implementing the builder interface. One solution is to parameterize the builder, that way by passing different parameters you get a different robots. However, you can also create a bunch of different concrete builders and the Director will call the same methods on the different concrete builders since they implement the builder interface.
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?
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.
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
rahul nangia Good point. Follow up question: since the RobotEngineer has all the required information at creationtime, would it be worse to make the robot in the constructor of the RobotEngineer?
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?
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.
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.
Do we need an interface for the director here (RobortEng.. implements RobotPlan) or is it due to langage Java (we may not need interface if we used C++). I know that it is better for maintenance and extension Like SOLID stands for :)
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 ?
Excuse me, can I question? Is this pattern fit in situation when products have different types and number of class fields (this video shows situation when every product has equal number of fields). If its fit, how to build it in this case? How to work with product after it was produced (do we need to create interface for products? How?)?May be you have some video for this situation ? Thank you! PS: For example if you have one robot with build in dynamics for dynamics (he can talk) and another one doesn't have it? how to impalement builder pattern (Of course, if this pattern fits) that will produce this two types of PC?
Hey Derek, excellent explanation of the GoF Builder Pattern. Do you know of any place in the JDK where it is used? I've found plenty of places where the Effective Java "Simple Builder" is used, but am scratching my head to find an application of the GoF Builder.
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.
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.
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
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?
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
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.
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") } } ```
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.
In this implementation, calling robotEngineer.makeRobot() several times will always return the same instance of Robot. One has to create new oldRobotBuilder and robotEngineer objects for each new robot object to be built. Is it supposed to be like that? Also, what is the reason for makeRobot() to be a method of robotEngineer and not of oldRobotBuilder()?
aha! checked the book - done the gang of four way, OldRobotBuilder would have a small additional method OldRobotBuilder.startBuilding() { this.robot = new Robot(); } called by director for each new build
now once we get the object of robot in TestRobotBuilder's main class... then we can call setRobotHead method.. is it legal ? .. the set method should have been accessible only with in Builder class na ? Please guide me.
Yes, you caught the code smell right. It's not about legal or illegal access, it about wrong abstraction. Though, It's not as serious as caller setting the properties explicitly but from abstraction makeRobot. Explicit trigger to builder to make the same is the smell. RobotBuilders responsibilty is : On request with desired properties from client, shall build and return Robot. Reiterating from one of the comment reply above: Builder provides the Client flexibility to set only required capabilities as per client need and return the Object based on the same. example Person jerry= new Person(Name,DOB, X,Y,Z,null,null,abc); Using Builder PersonBuilder personbuilder = PersonBuilder.getBuilder(); personbuilder .add(name).add(DOB).add(salary); Person jerry= personbuilder .getPerson();
But in this way for creating more than one robots shouldn't I create more than one engineers? If I use engineer's makeRobot() method over and over again shouldn't I get reference to same object?
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.
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 :)
Would it be an improvement if we set RobotEngineer as an interface providing a method createRobot()? Looks like it's combination of Builder and AbstractFactory and more powerful. :)
+James Rao Using a factory to produce children of a generic RobotEngineer instead of using exclusively this one can only serve one obvious purpose...changing the build method. (Since the get method is simple delegation and nobody wants to change that.) But if we want to do that, we can just use a different builder. And when you look at that it reveals a fault about this implementation...the engineer knows about the various methods that the builder uses. This can't be good, right? That's hardcoding the building process inside the engineer. The engineer should not have to know any of that (in real life, it's ultimately the engineer building, but...OOP is not real life). I think the engineer should instead call the build method of the builder and let the builder call each of its methods. Once that's done, there is no apparent need to abstract the RobotEngineer any further.
+Brax1982 Yes what I mean is to make the build process flexible by setting Engineer's createRobot abstract. The advantage is to prevent the build process from being hard coded. I know your meaning as transferring the building process from engineer to builder itself. But I don't think it is Builder pattern anymore as it regards builder as a comopents supplier instead of an engineer who knows how to build. In fact only the engineer knows the whole process and it uses builder as its components to build a robot. If we transfer the build process to builder itself, it would be like a strategy or factory or adapter design. Both of them are good for different scenes.
James Rao As far as I can see, all we are doing with this is introduce some coupling of the engineer class to the builder class. The methods called from inside the makeRobot method are members of the builder class. That class knows its own methods, so why would we not have it call them? From what I gather, the idea of the builder pattern is that we can switch "manuals" for constructing something out of a set of steps, the "plan". Make the whole robot, make one without arms and so on. We need the engineer as an exposed class (boundary) to receive the builders which are hidden from the user and start the build. Actually doing what another class can do and increase coupling...I see no value in that. I need to research this pattern, I guess.
+Brax1982 I believe the point is that the engineer knows how to build while the builder itself doesn't. The engineer is like a factory to assemble the robot with assistance of a builder who will supply the components. The builder itself is only a component supplier. It only defines each station with its concrete method but doesn't know how to assemble a whole robot as a product.
James Rao Thanks for explaining your interpretation again, although I understood it the first time around. =) But that's the thing...the builder DOES know how to build. The methods are inside the builder class. Building is just a matter of calling those methods in order. There is no reason that I can see for another class to call the methods inside the builder class.
Hi Derek I noticed RobotBuilder constructors don'st have any parameters And its build buildRobotxxx(); (buildRobotHead()) methods don’t have any parameters either Is this part of the encapsulation builder’s design? or could parameters be part of the builder ?
mmm, I tought that the builder pattern was to avoid the telescoping constructor anti-pattern, what's the difference between this(the one from the video), and this one: en.wikipedia.org/?title=Builder_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 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
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 :)
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?
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
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!
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
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 ^^
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
"Wololo, internet and welcome to part 8..."
This gave me a good chuckle.
I hn hn..
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 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.
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
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.
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
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 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.
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
Best Think about your videos is "They are not boring!!!"
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.
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
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
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 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++ :)
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 :)
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 :)
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).
I made another tutorial on the abstract factory pattern. Check out the last part of my refactoring tutorial. It should help
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.
Hats Off Boss !!!! You keep us afloat.
This will help me a lot with the library i'm trying to make in java!
Thank you so much!
You're very welcome :)
Thanks again to take your time and doing this free recalls mate!! Really appreciated
+Ewerton Silveira You're very welcome :)
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();
What is the advantage to this over having different enums for different robot types?
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 ..
Thank you :) I apologize, but I'm not understanding your question. Sorry about that
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
Hi, Why not set the get methods of the robot class in the robotplan interface?
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?
Your videos are really amazing I really appreciate the info thank you🙂
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
I have no idea why they were randomly blocking my RUclips videos?
Would the builder pattern be the correct choice for an Order Calculator that subtotals products purchased, total tax and total purchase amount/
Why do we need the RobotEnginner? Also, why should the builder create an object? Should it not be independent of creating the object?
The Engineer decouples the client from the Builder. The job of the Builder is to build the complex object. It's better that the builder it since the alternative is that the client do it.
Imagine a factory with no engineer or no director.
Imagine a Tesla Inc. factory with all those automated machines without Musk and team to assemble different parts.
Different parts of the factory / or even different factories manufacture different parts with different specs
The engineer assembles then.
I think the key thing is the builder vs the assembler. The Concrete Robot Builder assembles all the right manufactured parts
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.
You're saving my life man. Maybe I'll do my project now ;) Thank you!
I'm very happy I could help :)
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
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.
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?
Amazing explanation Derek!, a video is definitely a lot more helpful than the wikibooks
Cal Ferns Thank you for the compliment :)
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.
Thank you :) I don't know how I attracted so many nice people to my community
Hello! If I need to create a new kind of robot, what should i do? for example, this new robot had head, no arms , torso and three legs. How can i make this? Should I create a new class of robot who implements RobotBuilder? Or may the director(robotEngineer) can do this? I'm confusse
I forgot, great tutorial! :)
Great tutorial, thank you very much. This helped my my software project for college look alot more tidy and professional!
When you inject the RobotBuilder into the RobotEngineer, you are forcing that instance of the RobotEngineer to only make that one kind of the Robot. Why can't you instantiate your engineer without passing it a plan, and then pass the RobotBuilder to the makeRobot() method of the engineer?
This way, you can use the same engineer to create multiple different types of robots. Why would you choose the former (mentioned in your video) method?
+Kousha Talebian But in this implementation the makeRobot method is specifically calling the build methods of the builder that got passed. You would have to know the methods of the builder you get passed later on. That is not possible. The coupling to the builder needs to exist, anyway. So you create it right at construction time.
Or you go one step further and let the makeRobot method only delegate to the makeRobot method inside the builder which then calls all its own methods. If you want to build more or less, then you need a different builder.
Actually it is possible since the concrete builder is implementing the builder interface. One solution is to parameterize the builder, that way by passing different parameters you get a different robots. However, you can also create a bunch of different concrete builders and the Director will call the same methods on the different concrete builders since they implement the builder interface.
is it possible to have multiple builders? if so, how would look like?
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.
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
Would it be a worse design to let makeRobot immediately return the Robot object as well?
Gilliam Flebus A method does only what its name tells it does
rahul nangia Good point. Follow up question: since the RobotEngineer has all the required information at creationtime, would it be worse to make the robot in the constructor of the RobotEngineer?
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?
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
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.
Do we need an interface for the director here (RobortEng.. implements RobotPlan) or is it due to langage Java (we may not need interface if we used C++).
I know that it is better for maintenance and extension Like SOLID stands for :)
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 ?
MVC is coming! Thank you :)
Hi, Derek
On what part is where the RobotPlan interface comes into play?
I love your vids.
Excuse me, can I question? Is this pattern fit in situation when products have different types and number of class fields (this video shows situation when every product has equal number of fields). If its fit, how to build it in this case? How to work with product after it was produced (do we need to create interface for products? How?)?May be you have some video for this situation ? Thank you!
PS: For example if you have one robot with build in dynamics for dynamics (he can talk) and another one doesn't have it? how to impalement builder pattern (Of course, if this pattern fits) that will produce this two types of PC?
You're very welcome :) I'm glad to have been a help
Also, i can get only one robot from this, right? If i wanted another robot i would need to create another builder, (thus another engineer). Right?
+Danon W No you can create numerous robots withut the need for additional builders. Play with the code and the output and it will make sense.
Not necessarily since if you add parameters to the builder then the builder should be able to make different robots.
Hey Derek, excellent explanation of the GoF Builder Pattern. Do you know of any place in the JDK where it is used? I've found plenty of places where the Effective Java "Simple Builder" is used, but am scratching my head to find an application of the GoF Builder.
Thank you :) Sorry, but I don't know of an example
Dude, you are awesome. Subscribed.
Jason Lough Thank you very much :)
Thanks for this. Very useful.
Thank you very much :) I did my best
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.
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.
Where can I get the diagrams you use to show the scheme/layout of these designs? They are extremely helpful.
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
problems with nullpointerexception if makerobot function is not called.
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
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.
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")
}
}
```
Thanks for backing me up, but it doesn't bother me :)
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.
In this implementation, calling robotEngineer.makeRobot() several times will always return the same instance of Robot. One has to create new oldRobotBuilder and robotEngineer objects for each new robot object to be built. Is it supposed to be like that?
Also, what is the reason for makeRobot() to be a method of robotEngineer and not of oldRobotBuilder()?
aha! checked the book - done the gang of four way, OldRobotBuilder would have a small additional method OldRobotBuilder.startBuilding() { this.robot = new Robot(); } called by director for each new build
I'm very happy to help :)
Derek Bananas thanks for the video!
Thank you :) I'm happy I could help
now once we get the object of robot in TestRobotBuilder's main class... then we can call setRobotHead method.. is it legal ? .. the set method should have been accessible only with in Builder class na ? Please guide me.
Yes, you caught the code smell right. It's not about legal or illegal access, it about wrong abstraction.
Though, It's not as serious as caller setting the properties explicitly but from abstraction makeRobot.
Explicit trigger to builder to make the same is the smell.
RobotBuilders responsibilty is : On request with desired properties from client, shall build and return Robot.
Reiterating from one of the comment reply above:
Builder provides the Client flexibility to set only required capabilities as per client need and return the Object based on the same.
example
Person jerry= new Person(Name,DOB, X,Y,Z,null,null,abc);
Using Builder
PersonBuilder personbuilder = PersonBuilder.getBuilder();
personbuilder .add(name).add(DOB).add(salary);
Person jerry= personbuilder .getPerson();
But in this way for creating more than one robots shouldn't I create more than one engineers? If I use engineer's makeRobot() method over and over again shouldn't I get reference to same object?
i can not find any chapter in Headfirst Design Pattern that talk about Builder.
I cover the patterns found in the GOF book amzn.to/2oLWxX9
Nice videos. Thanks a lot
Iyyappan N Thank you :) You're very welcome
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 so much for this great tutorial
+Mohammed Hashim You're very welcome :)
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 :)
Would it be an improvement if we set RobotEngineer as an interface providing a method createRobot()? Looks like it's combination of Builder and AbstractFactory and more powerful. :)
+James Rao Using a factory to produce children of a generic RobotEngineer instead of using exclusively this one can only serve one obvious purpose...changing the build method. (Since the get method is simple delegation and nobody wants to change that.) But if we want to do that, we can just use a different builder.
And when you look at that it reveals a fault about this implementation...the engineer knows about the various methods that the builder uses. This can't be good, right? That's hardcoding the building process inside the engineer. The engineer should not have to know any of that (in real life, it's ultimately the engineer building, but...OOP is not real life).
I think the engineer should instead call the build method of the builder and let the builder call each of its methods. Once that's done, there is no apparent need to abstract the RobotEngineer any further.
+Brax1982 Yes what I mean is to make the build process flexible by setting Engineer's createRobot abstract. The advantage is to prevent the build process from being hard coded. I know your meaning as transferring the building process from engineer to builder itself. But I don't think it is Builder pattern anymore as it regards builder as a comopents supplier instead of an engineer who knows how to build. In fact only the engineer knows the whole process and it uses builder as its components to build a robot. If we transfer the build process to builder itself, it would be like a strategy or factory or adapter design. Both of them are good for different scenes.
James Rao As far as I can see, all we are doing with this is introduce some coupling of the engineer class to the builder class. The methods called from inside the makeRobot method are members of the builder class. That class knows its own methods, so why would we not have it call them?
From what I gather, the idea of the builder pattern is that we can switch "manuals" for constructing something out of a set of steps, the "plan". Make the whole robot, make one without arms and so on. We need the engineer as an exposed class (boundary) to receive the builders which are hidden from the user and start the build.
Actually doing what another class can do and increase coupling...I see no value in that. I need to research this pattern, I guess.
+Brax1982 I believe the point is that the engineer knows how to build while the builder itself doesn't. The engineer is like a factory to assemble the robot with assistance of a builder who will supply the components. The builder itself is only a component supplier. It only defines each station with its concrete method but doesn't know how to assemble a whole robot as a product.
James Rao Thanks for explaining your interpretation again, although I understood it the first time around. =)
But that's the thing...the builder DOES know how to build. The methods are inside the builder class. Building is just a matter of calling those methods in order. There is no reason that I can see for another class to call the methods inside the builder class.
Please cover the Model-View-Controller design pattern, and keep up the great work
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
Hi Derek
I noticed RobotBuilder constructors don'st have any parameters
And its build buildRobotxxx(); (buildRobotHead()) methods don’t have any parameters either
Is this part of the encapsulation builder’s design?
or could parameters be part of the builder ?
mmm, I tought that the builder pattern was to avoid the telescoping constructor anti-pattern, what's the difference between this(the one from the video), and this one: en.wikipedia.org/?title=Builder_pattern ?