新运营商在哪些方面被认为是有害的?

In what terms does new operator is considered harmful?

当使用 new 运算符创建对象被认为是有害的时,应该使用工厂模式。在什么情况下 new 运算符被认为是有害的

你使用工厂模式的主要原因是你不需要一个对象的很多构造函数;

public Person(int age, String firstName, String lastName);
public Person(int age, String firstName, String middleName, String lastName);
public Person(int age, String firstName, String lastName, String socialNumber);
....

使用工厂模式,您可以创建许多不同的对象,这些对象使用不同的参数进行初始化,而无需编写那么多构造方法。

new object() 通常用于创建对象的实例以使用它的非静态方法。我阅读了有关使用 new 运算符的一些问题以及它如何分配堆内存(您可能不希望这样)。忽略使用 new 没有问题。

        Using of new operator directly is hardcoding. 
        It also means that class is not following single responsibility principle.

        Factories along with interfaces allow long term flexibility.
     It allows decoupling and therefore more testable design.  
        It allows you to introduce an Inversion of Control (IoC) container easily
        It makes your code more testable as you can mock interfaces
        It gives you a lot more flexibility when it comes time to change the application (i.e. you can create new implementations without changing the dependent code). 
Hope this helps.

new 不被认为是有害的。

如果要创建 class 的新实例,您需要使用 new 某处 。是否将 new 的使用包装在工厂中是一个 design/architecture 问题。

您可能指的是到处都是 "newing up"(使用 new SomeClass(..) 创建实例)实例,通常被认为是糟糕的设计/糟糕的做法。这样做的原因是,将来更改实现会更加困难,因为您所有的 classes 都是 紧密耦合的 。一个非常常用的 argument/example 是 testing。如果您直接在代码中创建新实例,则可能更难单独测试该代码 and/or 使用某些 classes 的模拟。

我建议您阅读支持(和反对)使用 Dependency Injection 的论据。

有时您不能依赖注入到您的 class 中的单个实例。有时您需要 才能按需创建一个(或多个)新实例。在这些情况下,如果您想避免直接使用 new,那么研究各种工厂模式是有意义的,以此来提取创建新实例的责任。

是否遵循此类做法完全取决于您 and/or 您的团队。

框架需要为一系列应用程序标准化架构模型,但允许各个应用程序定义自己的域对象并提供它们的实例化。

通常,Java 或某些语言中的对象创建过程如下:

SomeClass someClassObject = new SomeClass();

上述方法的问题是使用 SomeClass’s 对象的代码现在突然变得依赖于 SomeClass 的具体实现。使用 new 创建对象没有错,但它带来了将我们的代码与具体实现紧密耦合的包袱 class,这偶尔会出现问题。