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

时间:2016-10-15 15:46:24

标签: java factory-pattern

当使用new operator创建对象被认为是有害的时,应该使用工厂模式。新运营商在哪些方面被认为是有害的

4 个答案:

答案 0 :(得分:4)

new不被视为有害。

如果要创建类的新实例,则需要在某处使用new 。是否在工厂中使用new是一个设计/架构问题。

你可能指的是在整个地方“newing up”(通过使用new SomeClass(..))实例创建一个实例,通常被认为是糟糕的设计/糟糕的做法。这样做的原因是,将来更改实现可能会更困难,因为所有类都是紧密耦合。使用的一个非常常见的参数/示例是 testing 。如果直接在代码中创建新实例,则可能更难以单独测试该代码和/或使用某些类的模拟。

我建议您使用Dependency Injection阅读(和反对)的参数。

有时你不能依赖注入你班级的单个实例。有时您需要能够按需创建新实例(或多个)。在这些情况下,如果您想避免直接使用new,那么查看各种工厂模式作为提取创建新实例的责任的方法是有意义的。

您是否遵循此类行为完全取决于您和/或您的团队。

答案 1 :(得分:1)

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

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没有问题。

答案 2 :(得分:0)

        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.

答案 3 :(得分:0)

框架需要标准化一系列应用程序的体系结构模型,但允许单个应用程序定义自己的域对象并为其实例化。

通常,用Java或某些语言创建对象的方式如下:

SomeClass someClassObject = new SomeClass();

上述方法的问题在于,使用SomeClass’s对象的代码现在突然变得依赖于SomeClass的具体实现。使用new来创建对象并没有错,但是它伴随着将我们的代码紧密耦合到具体的实现类的负担,这有时可能会出现问题。