简体   繁体   English

如果您不给新关键字命名,新关键字如何工作?

[英]how does the new keyword work if you dont give it a name?

I'm learning the Builder Pattern design pattern. 我正在学习“构建器模式”设计模式。 I understand most of it but I'm just having confusion with the new keyword. 我了解其中的大部分内容,但对new关键字感到困惑。 In this tutorial, in the MealBuilder class, he creates an object of type Meal, and then calls a method addItem(...) using that object. 在本教程中,他在MealBuilder类中创建了Meal类型的对象,然后使用该对象调用方法addItem(...) 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. 我知道new关键字创建了一个类的实例(实例又是一个用于创建对象的词吗?),但他没有给它命名。 Eg I understanding the following: Meal mealobject = new Meal(); 例如,我了解以下内容: Meal mealobject = new Meal(); but I dont understand this: new ChickenBurger(); 但我不明白这一点: 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. 在某些情况下,您可能会决定对表达式使用命名引用将有助于阐明代码的功能,尤其是在数据类型不清楚的情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM