java 简单来说,什么是工厂?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7550612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:26:58  来源:igfitidea点击:

In simplest terms, what is a factory?

javadesign-patternsfactory

提问by BalusC

What is a factory and why would I want to use one?

什么是工厂,我为什么要使用工厂?

回答by BalusC

Are you familiar with JDBC? It's one and all (abstract) factory. It's a good real world example.

你熟悉JDBC吗?这是一个和所有(抽象)工厂。这是一个很好的现实世界的例子。

// Factory method. Loads the driver by given classname. It actually returns a 
// concrete Class<Driver>. However, we don't need it here, so we just ignore it.
// It can be any driver class name. The MySQL one here is just an example.
// Under the covers, it will do DriverManager.registerDriver(new Driver()).
Class.forName("com.mysql.jdbc.Driver");

// Abstract factory. This lets the driver return a concrete connection for the
// given URL. You can just declare it against java.sql.Connection interface.
// Under the covers, the DriverManager will find the MySQL driver by URL and call
// driver.connect() which in turn will return new ConnectionImpl().
Connection connection = DriverManager.getConnection(url);

// Abstract factory. This lets the driver return a concrete statement from the
// connection. You can just declare it against java.sql.Statement interface.
// Under the covers, the MySQL ConnectionImpl will return new StatementImpl().
Statement statement = connection.createStatement();

// Abstract factory. This lets the driver return a concrete result set from the
// statement. You can just declare it against java.sql.ResultSet interface.
// Under the covers, the MySQL StatementImpl will return new ResultSetImpl().
ResultSet resultSet = statement.executeQuery(sql);

You do not need to have a single line of JDBC driver specific importin your code. You do not need to do import com.mysql.jdbc.ConnectionImplor something. You just have to declare everything against java.sql.*. You do not need to do connection = new ConnectionImpl();yourself. You just have to get it from an abstract factory as part of a standard API.

您不需要import在代码中包含一行特定的 JDBC 驱动程序。你不需要做什么import com.mysql.jdbc.ConnectionImpl或什么。你只需要声明一切反对java.sql.*. 你不需要connection = new ConnectionImpl();自己做。您只需要从抽象工厂中获取它作为标准 API 的一部分。

If you make the JDBC driver class name a variable which can be configured externally (e.g. properties file) and write ANSI compatible SQL queries, then you do not ever need to rewrite, recompile, rebuild and redistribute your Java application for every single database vendor and/or JDBC driver which the world is aware of. You just have to drop the desired JDBC driver JAR file in the runtime classpath and provide configuration by some (properties) file without the need to change any line of Java code whenever you want to switch of DB or reuse the app on a different DB.

如果您使 JDBC 驱动程序类名称成为一个可以在外部配置的变量(例如属性文件)并编写与 ANSI 兼容的 SQL 查询,那么您永远不需要为每个数据库供应商重写、重新编译、重建和重新分发您的 Java 应用程序和/ 或全世界都知道的 JDBC 驱动程序。您只需要在运行时类路径中删除所需的 JDBC 驱动程序 JAR 文件并通过某些(属性)文件提供配置,而无需更改任何 Java 代码行,只要您想切换 DB 或在不同的 DB 上重用应用程序。

That's the power of interfaces and abstract factories.

这就是接口和抽象工厂的力量。

Another known real world example is Java EE. Substitute "JDBC" with "Java EE" and "JDBC driver" with "Java EE application server" (WildFly, TomEE, GlassFish, Liberty, etc).

另一个已知的真实世界示例是 Java EE。将“JDBC”替换为“Java EE”,将“JDBC 驱动程序”替换为“Java EE 应用程序服务器”(WildFly、TomEE、GlassFish、Liberty 等)。

See also:

也可以看看:

回答by eabraham

The Factory design pattern is ideal in circumstances when you need to create multiple instances of an object at run time. Rather than explicitly creating each instance you can initialize many instances. Additionally, you can encapsulate complex creation code that can be reused multiple times.

当您需要在运行时创建对象的多个实例时,工厂设计模式是理想的选择。您可以初始化许多实例,而不是显式创建每个实例。此外,您可以封装可以多次重用的复杂创建代码。

Example:

例子:

public class Person {
    int ID;
    String gender;
    public Person(int ID,String gender){
        this.ID=ID;
        this.gender=gender;
    }
    public int getID() {
        return ID;
    }
    public String getGender() {
        return gender;
    }
}
public class PersonFactory{
    public static Person createMale(int id){
        return new Person(id,"M");
    }
    public static Person createFemale(int id){
        return new Person(id,"F");
    }
}
public class factorytest{
    public static void main(String[]args){
        Person[] pList= new Person[100];
        for(int x=0;x<100;x++){
            pList[x]=PersonFactory.createMale(x);
        }
    }
}

In this example we encapsulate the details of the gender initialization parameter and can simply ask the PersonFactory to createMale or createFemale Person objects.

在这个例子中,我们封装了性别初始化参数的细节,可以简单地要求 PersonFactory 去 createMale 或 createFemale Person 对象。

回答by Saket

In simple terms, Factoryis an OO design pattern that deals with creating objects without specifying the exact class of objectthat is to be created.

简单来说,工厂是一种 OO 设计模式,它处理创建对象而不指定要创建的对象的确切类

A good reason to use it is well defined in wikipedia:

使用它的一个很好的理由在 wikipedia 中有很好的定义:

The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

对象的创建通常需要复杂的过程,不适合包含在组合对象中。对象的创建可能会导致大量的代码重复,可能需要组合对象无法访问的信息,可能无法提供足够的抽象级别,或者可能不是组合对象关注的一部分。工厂方法设计模式通过定义用于创建对象的单独方法来处理这些问题,然后子类可以覆盖这些方法以指定将创建的产品的派生类型。

回答by Shahzeb

What is a factory ?

什么是工厂?

Wikipediaexplains in detail

维基百科详细解释

Also see answer from legendary BalusCover hereabout many GoF patterns examples
In simple words Factory creates\initialize\allocate the objects that you can use in the code.
e.g if you have a person abstract class or interface or even a concrete class and you declare it in an other class e.g. private person;that is just that object has been declared but not created. You will either use new or some dependency injection or a factory to create this object (there are other options as well e.g Locator etc).

还看到传说中的答案BalusC这里对多GOF模式的例子
在简单的话厂创建\初始化。\分配,你可以在代码中使用的对象。
例如,如果您有一个人的抽象类或接口,甚至是一个具体的类,并且您在另一个类中声明它,例如private person;,该对象已被声明但尚未创建。您将使用新的或某些依赖项注入或工厂来创建此对象(还有其他选项,例如 Locator 等)。

Why would I want to use one?

为什么我要使用一个?

Now you might need to a have specific type of person e.g teacher or even person might have different implantation based of different configurations etc .Factory pattern takes care of this.It allows you or should I say frees you from worrying about what implementation or initialization of particular class should be used.

现在你可能需要一个特定类型的人,例如老师,甚至一个人可能有基于不同配置等的不同植入。工厂模式负责这个。它让你或者我应该说让你不用担心什么实现或初始化应该使用特定的类。

回答by Alex Abdugafarov

The factory is an object, that creates objects. The common usage includes two cases:

工厂是一个创建对象的对象。常见的用法包括两种情况:

  • When you want to delegate the choice of the concrete object to the factory - e.g. it may return an already existing object (see Integer.valueOf(), which is a so-called factory method) or choose a concrete implementation depending on some conditions - e.g. supplied argument or pre-defined options (see XPathFactoryclass in Java API for XML Processing)
  • When you want more flexibility for some universal job. You cannot pass a method or a constructor as an argument (well, you can, but reflection sucks), so you use a concrete factory as an object source (e.g. SomeFactory<T>in a generic method).
  • 当您想将具体对象的选择委托给工厂时 - 例如,它可能返回一个已经存在的对象(请参阅Integer.valueOf(),这是所谓的工厂方法)或根据某些条件选择具体实现 - 例如提供的参数或预-defined选项(请参阅XPathFactory的Java API用于XML处理
  • 当您想要为某些通用工作提供更多灵活性时。您不能将方法或构造函数作为参数传递(好吧,您可以,但反射很糟糕),因此您使用具体工厂作为对象源(例如SomeFactory<T>,在泛型方法中)。

回答by Ravindra babu

Factoryis an object for creating other objects.

工厂是用于创建其他对象的对象。

It creates objects without exposing the instantiation logic to the client.

它在不向客户端公开实例化逻辑的情况下创建对象。

Use this pattern when you don't want to expose object instantiation logic to the client/caller

当您不想向客户端/调用者公开对象实例化逻辑时使用此模式

Related posts:

相关文章:

Design Patterns: Factory vs Factory method vs Abstract Factory

设计模式:工厂 vs 工厂方法 vs 抽象工厂

What is the basic difference between the Factory and Abstract Factory Patterns?

工厂模式和抽象工厂模式之间的基本区别是什么?