gpt4 book ai didi

java - 实例工厂方法与静态工厂方法

转载 作者:IT老高 更新时间:2023-10-28 20:47:07 24 4
gpt4 key购买 nike

不能所有的工厂方法都是静态的吗?生产产品的东西是否需要状态?什么时候适合使用实例工厂或静态工厂方法?你能提供区分这两者的例子吗?

最佳答案

假设“实例工厂方法”实际上是指 GoF“工厂方法”,Joshua Bloch 在他的“Effective Java”一书中描述了术语“静态工厂方法”。谷歌搜索我到达了这些网站:

希望它有助于使差异更加清晰。

听从 Marvo 的建议:

  • GoF 中所述的工厂方法:

    define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

示例(Java 代码):

    public abstract class Product { ... }

public class ConcreteProduct extends Product { ... }

public abstract class Creator {
public void anOperation() { ... product = factoryMethod(); ... }
public abstract Product factoryMethod();
}

public class ConcreteCreator extends Creator {
public Product factoryMethod() { return new ConcreteProduct(); }
}
  • Effective Java 中所述的静态工厂方法:

    A class can provide a public static factory method, which is simply a static method that returns an instance of the class. (...) One advantage of static factory methods is that, unlike constructors, they have names. (...) A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked. (...) A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. (...) The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.

示例(Java 代码):

    public class Boolean {
...
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
...
}

关于java - 实例工厂方法与静态工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8147163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com