接口类java中的静态工厂方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20563796/
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-08-13 02:50:36  来源:igfitidea点击:

static factory method in interface class java

javastatic-factory

提问by Manu Viswam

I was reading Effective javatext book. First item is about using static factory methods instead of public constructor. My doubt is that if i am specifying an Interfacehow can i specify a static factory method in the Interface? Because java does not support static methods inside interface. The text book specifies about creating a non-instantiable classcontaining the public static factory methods. But how can those method access the private constructor of the implementation class?

我正在阅读Effective java教科书。第一项是关于使用静态工厂方法而不是公共构造函数。我的疑问是,如果我指定了一个Interface如何在Interface? 因为java里面不支持静态方法interface。教科书指定了如何创建包含公共静态工厂方法的不可实例化类。但是这些方法如何访问实现类的私有构造函数呢?

The text book says if you are defining an Interface Type, create a non-instantiable class Typesand include the static factory methods in that class. But how can a method defined in the Typesclass access the private constructor of a concrete implementation of Interface Type

教科书说,如果您要定义一个Interface Type,请创建一个不可实例化的类Types并在该类中包含静态工厂方法。但是Types类中定义的方法如何访问具体实现的私有构造函数Interface Type

EDIT:- Below sentence is quoted from the text book. Please explain me its meaning

编辑:-下面的句子是从教科书中引用的。请解释一下它的意思

"Interfaces can't have static methods, so by convention, static factory methods for an interface named Typeare put in a noninstantiable class (Item 4) named Types"

“接口不能有静态方法,因此按照惯例,名为Type的接口的静态工厂方法放在名为Types 的不可实例化类(第 4 项)中”

EDIT:- taken from Effective Java By Joshua Bloch: Item1 - Static Factory Method

编辑:- 取自约书亚 Bloch 的 Effective Java:Item1 - 静态工厂方法

     public interface Foo{ //interface without plural 's' (question 1)
     public void bar();
 }
 public abstract class Foos(){ // abstract factory with plural 's' (question 1)
    public static Foo createFoo(){
        return new MyFoo();
    }
    private class MyFoo implements Foo{ // a non visible implementation (question 2)
       public void bar(){}
    }
 }

My question is that how can the static method createFoo()calls the private constructor of MyFoo

我的问题是静态方法如何createFoo()调用私有构造函数MyFoo

采纳答案by Tim B

You can define the factory as returning the Interface but internally it creates a concrete class.

您可以将工厂定义为返回接口,但在内部它会创建一个具体的类。

For example:

例如:

public Interface I { }

private class Impl implements I {
}

I buildI() {
    return new Impl();
}

The trick is to create the implementations with package private (or even if they are inner classes private) constructors and then only the factory can build them.

诀窍是使用包私有(或者即使它们是内部类私有)构造函数创建实现,然后只有工厂可以构建它们。

The power of this method is that the factory can build the appropriate implementation depending on the requirements and that all happens invisibly to the user. For example when you create an EnumSetusing the factory there are multiple internal implementations depending on how many entries there are in the Enumthat the EnumSetis being built for. A super-fast version using bitfields on a long for Enumswith less than 64 entries, a slower version for longer enumerations.

这种方法的强大之处在于工厂可以根据需求构建适当的实现,并且这一切都发生在用户不可见的地方。例如,当你创建一个EnumSet工厂使用有多个内部实现取决于有多少项有在EnumEnumSet正在修建的。一个使用位域的超快速版本,用于Enums少于 64 个条目的 long for ,一个较慢的版本用于更长的枚举。

To specify the interface for a factory all you need to do is:

要为工厂指定接口,您需要做的就是:

public interface Factory {
   I buildI();
}

Now people can call you with setFactory(new FactoryImpl());you can then call factory.buildI()and their code then returns the concrete implementation.

现在人们可以打电话给你,setFactory(new FactoryImpl());你可以打电话factory.buildI(),他们的代码然后返回具体的实现。

You can take this a step further and use Generics:

您可以更进一步并使用泛型:

public interface GenericFactory<T> {
    T buildInstance();
}

And then your setFactorybecomes:

然后你setFactory变成:

public void setFactory(GenericFactory<I> factory);

To create a factory they do:

要创建工厂,他们会执行以下操作:

public class FactoryImpl implements GenericFactory<I> {
     @override
     I buildInstance() {
        return new impl();
     }
}

But now you can use that same factory class for absolutely anything that needs a factory, just change the generics requirement.

但是现在您可以将相同的工厂类用于绝对需要工厂的任何事物,只需更改泛型要求即可。

The reason it can call the private constructor is very simple - it's declared in the same class!

它可以调用私有构造函数的原因很简单——它是在同一个类中声明的!

Inside one Java file you can create the class with the private constructor. You then define the static method inside the class and even though it is static it still has the privileges required to access the constructor.

在一个 Java 文件中,您可以使用私有构造函数创建类。然后在类中定义静态方法,即使它是静态的,它仍然具有访问构造函数所需的权限。

If the factory and implementation are in separate classes then they will be placed in the same package and the method made package private instead of private.

如果工厂和实现在不同的类中,那么它们将被放置在同一个包中,并且该方法将包设为私有而不是私有。

回答by AurA

It talks about creating object via static factory method in the implementation not the interface

它谈论通过实现中的静态工厂方法而不是接口创建对象

public Interface MyInterface {
    public void myFunction();
}

public class MyClass implements MyInterface {

    // constructor is made private
    private MyClass() {}

    // Use this to create object instead use static factory
    public static MyClass getInstance() {
        return new MyClass();
    }

    public void myFunction(){
      // your implementation
    } 
}

A previous post also talks about static factory method.. What are static factory methods?

之前的一篇文章也谈到了静态工厂方法。什么是静态工厂方法?

Apart from the book I also find the undermentioned link a good read http://www.javacodegeeks.com/2013/01/static-factory-methods-vs-traditional-constructors.html

除了这本书,我还发现下面提到的链接很好读 http://www.javacodegeeks.com/2013/01/static-factory-methods-vs-traditional-constructors.html

回答by Grodriguez

You cannot define a factory method in an interface, but you cannot have a constructor in an interface either: Interfaces cannot be instantiated. The point is to use a factory method instead of a constructor in the classes implementing the interface, not in the interface itself.

您不能在接口中定义工厂方法,但也不能在接口中具有构造函数:接口不能被实例化。关键是在实现接口的类中使用工厂方法而不是构造函数,而不是在接口本身中。

回答by Manu Viswam

This problem is solved in JAVA 8. Now interfaces can have static methods. More details here :- http://www.techempower.com/blog/2013/03/26/everything-about-java-8/

这个问题在JAVA 8中解决了。现在接口可以有静态方法了。更多细节在这里:- http://www.techempower.com/blog/2013/03/26/everything-about-java-8/