I'm learning the Builder Pattern design pattern. I understand most of it but I'm just having confusion with the new
keyword. In this tutorial, in the MealBuilder class, he creates an object of type Meal, and then calls a method addItem(...)
using that object. I don't understand what he passes in the parameter. I understand that the new
keyword creates an instance (is instance another word for creating an object?) of a class but he didn't name it. Eg I understanding the following: Meal mealobject = new Meal();
but I dont understand this: new ChickenBurger();
If you wrote
Meal meal = new Meal();
Item burger = new ChickenBurger();
meal.addItem(burger);
then this would behave the same way. However, if you aren't going to user the "burger" reference again, then there's no point in creating it. Just writing
Meal meal = new Meal();
meal.addItem(new ChickenBurger());
is simpler and makes it obvious to someone reading the code that the item is only being added to the collection (the meal).
Note that this isn't a hard rule. There may be some situations where you might decide that using a named reference for an expression will help clarify what the code is doing, particularly if it's not clear from the data types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.