gpt4 book ai didi

design-patterns - 工厂方法是哪个方法

转载 作者:行者123 更新时间:2023-12-04 07:18:38 25 4
gpt4 key购买 nike

我无法理解工厂方法模式。来自此处的示例:http://worldwardiary.com/history/Factory_method_pattern#Using_the_factory_pattern在这里:https://stackoverflow.com/a/806942/2420939 :

public class ImageReaderFactory 
{
public static ImageReader getImageReader( InputStream is )
{
int imageType = figureOutImageType( is );

switch( imageType )
{
case ImageReaderFactory.GIF:
return new GifReader( is );
case ImageReaderFactory.JPEG:
return new JpegReader( is );
// etc.
}
}
}

哪个是事实上的“工厂方法”:getImageReader() 或 GifReader 类的“<<”方法?

最佳答案

简而言之,工厂方法封装了对象的创建。 他们为您创建复杂的对象,因此您不必费心。

在你的例子中:

public class ImageReaderFactory {
public static ImageReader getImageReader(InputStream is) {
int imageType = figureOutImageType( is );
switch( imageType ) {
case ImageReaderFactory.GIF:
return new GifReader( is );
case ImageReaderFactory.JPEG:
return new JpegReader( is );
// etc.
}
}
}

谁在创建 ImageReader 对象(调用它们的构造函数)并返回它们? figureOutImageType()GifReader 类的方法(或其他 JpegReader 或可能的 PngReaderTiffReader, etcReader...).

最终getImageReader() 将为您创建它们。这就是您调用“嘿,请给我创建一个ImageReader的方法,剩下的就交给它了。

因此,充其量,public static ImageReader getImageReader(InputStream is) {} 是最接近工厂方法的(请参阅下面的更新)。



更新:

请记住,此设计严格来说是“工厂方法模式”。这is presented as a variant of it .

其原因已在 other answers 中讨论过。 , 所以请允许我 quote one here (稍微改编):

(...) this snippet is not a proper implementation of the "Factory Method OO Design Pattern", since it does not satisfy "a class defer instantiation to subclasses." Though, personally I would freely refer to this solution as "factory method".
To make it real factory method pattern, you need to allow the method to be overridden by subclasses. I.e. factory class (ImageReaderFactory) needs to be extensible (i.e. non-static), and getImageReader needs to be abstract.

关于design-patterns - 工厂方法是哪个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16753527/

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