工厂方法模式的适用性 [英] Applicability for the Factory Method Pattern

查看:35
本文介绍了工厂方法模式的适用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对工厂方法模式感到困惑.

I am confused at the factory-method pattern.

以下代码来自"https://www.oodesign.com/factory-method-pattern.html"

The below code is from "https://www.oodesign.com/factory-method-pattern.html"

public interface Product { � }

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

public class ConcreteProduct implements Product { � }

public class ConcreteCreator extends Creator 
{
    protected Product factoryMethod() 
    {
        return new ConcreteProduct();
    }
}

public class Client 
{
    public static void main( String arg[] ) 
    {
        Creator creator = new ConcreteCreator();
        creator.anOperation();
    }
}

在这里我很困惑:

Creator creator = new ConcreteCreator();

在站点中,我们在两种情况下都采用了这种模式

In the site, we apply this pattern in two cases

  1. 当类无法预期应该创建的对象的类型时
  2. 当类希望其子类成为特定于新创建对象的类型的子类时

但是在客户端代码中,我们在ConcreteCreator中添加了新"关键词(我知道这是混凝土产品的混凝土工厂).

But in the client code, we put 'new' keword with ConcreteCreator (and I know this is the concrete factory for the concrete product).

这不是说客户完全知道他/她需要创建哪种类型的对象?

Doesn't it mean that the client exactly know what type of object he/she need to create?

有人可以帮助我吗?

推荐答案

在工厂方法模式"中, Client 的作用是为以下操作提供具体的 Product :抽象的 Creator .

In the Factory Method Pattern, the role of the Client is to provide a concrete Product to the abstract Creator.

当抽象的 Creator 驻留在第三方库中并且要求每个 Client 通过实施来提供 Product 时,这才最有意义.它自己的子类.在这种情况下, Client 正在实现它不拥有的抽象.

This makes most sense when the abstract Creator lives in a third-party library and each Client is required to provide a Product by implementing its own subclass. In this scenario the Client is implementing an abstraction that it doesn't own.

Factory方法也可能很有用.

Factory Method could be useful even when the Client owns the abstraction, if it needs to create multiple subclasses (i.e. multiple Products).

Factory方法没有任何意义.

Factory Method does not make sense when the Client owns the abstraction and there is only one Product.

这篇关于工厂方法模式的适用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆