C# 什么时候使用工厂方法模式?

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

When to use Factory method pattern?

c#design-patternsfactory

提问by Jaswant Agarwal

When to use Factory method pattern?

什么时候使用工厂方法模式?

Please provide me some specific idea when to use it in project? and how it is a better way over new keyword?

请给我一些具体的想法什么时候在项目中使用它?以及它如何比 new 关键字更好?

采纳答案by Austin

Although this isn't necessarily it's primary use, it's good for something where you have specialized instances of a class:

虽然这不一定是它的主要用途,但它适用于您拥有类的专门实例的情况:

public ITax BuildNewSalesTax()
public ITax BuildNewValueAddedTax()

You need both methods to build a tax object, but you don't want to have to depend on using "new" everytime because the constructors may be complex. This way I encapsulate all of the changes into a single method that is clear to others for future maintenance.

您需要两种方法来构建税对象,但您不想每次都依赖于使用“new”,因为构造函数可能很复杂。通过这种方式,我将所有更改封装到一个方法中,其他人可以清楚地了解以备将来维护。

回答by Fredrik M?rk

I have two cases where I tend to use it:

我有两种情况,我倾向于使用它:

  1. The object needs to be initialized in some specific manner
  2. When I want to construct a specific type based on an abstract type (an abstract class or an interface).
  1. 对象需要以某种特定的方式初始化
  2. 当我想基于抽象类型(抽象类或接口)构造特定类型时。

Examples:

例子:

  1. First casecould be that you want to have a factory creating SqlCommandobjects, where you automatically attach a valid SqlConnectionbefore returning the command object.

  2. Second caseis if you have an interface defined and determine at execution time which exact implementation of the interface to use (for instance by specifying it in a configuration file).

  1. 第一种情况可能是您想要一个工厂创建SqlCommand对象,SqlConnection在返回命令对象之前自动附加一个有效的对象。

  2. 第二种情况是,如果您定义了一个接口并在执行时确定要使用该接口的哪个确切实现(例如通过在配置文件中指定它)。

回答by Jimmeh

To answer the second part of you question from my opinion, I think the reason it's better than the 'new' keyword is that the factory method reduces the dependancy on constructors of particular classes. By using a factory method, you delegate the creation of the object in question to someone else, so the caller doesn't need teh knowledge of how to create the object.

从我的观点回答你问题的第二部分,我认为它比 'new' 关键字更好的原因是工厂方法减少了对特定类的构造函数的依赖。通过使用工厂方法,您可以将相关对象的创建委托给其他人,因此调用者不需要了解如何创建对象。

回答by Dzmitry Huba

You can refer to section 9.5 Factories from Framework Design Guidelines 2nd Edition. Here is quoted set of guidelines with respect to using factories over constructors:

可以参考Framework Design Guidelines 2nd Edition中的9.5 Factories部分。这里引用了一组关于在构造函数上使用工厂的指南:

DO prefer constructors to factories, because they are generally more usable, consistent, and convenient than specialized construction mechanisms.

CONSIDER using a factory if you need more control than can be provided by constructors over the creation of the instances.

DO use a factory in cases where a developer might not know which type to construct, such as when coding against a base type or interface.

CONSIDER using a factory if having a named method is the only way to make the operation self-explanatory.

DO use a factory for conversion-style operations.

DO 更喜欢构造函数而不是工厂,因为它们通常比专门的构造机制更有用、更一致和更方便。

如果您需要比构造函数提供的更多控制权来创建实例,请考虑使用工厂。

在开发人员可能不知道要构造哪种类型的情况下,例如在针对基类型或接口进行编码时,请务必使用工厂。

如果具有命名方法是使操作不言自明的唯一方法,请考虑使用工厂。

务必使用工厂进行转换式操作。

And from section 5.3 Constructor Design

来自第 5.3 节构造函数设计

CONSIDER using a static factory method instead of a constructor if the semantics of the desired operation do not map directly to the construc- tion of a new instance, or if following the constructor design guidelines feels unnatural.

如果所需操作的语义没有直接映射到新实例的构造,或者如果遵循构造函数设计指南感觉不自然,请考虑使用静态工厂方法而不是构造函数。

回答by abhilash

It's better to have a factory method pattern vs new keyword. The idea is to move complete instantiation of objects outside the business logic. This principle is the crux of dependency injection. And, the work of the factory method can be delegated to a Dependency Injection Framework like Spring.net or Castle Windsor at a later point.

最好有工厂方法模式 vs new 关键字。这个想法是将对象的完整实例化移到业务逻辑之外。这个原则是依赖注入的关键。而且,工厂方法的工作可以在稍后委托给依赖注入框架,如 Spring.net 或 Castle Windsor。

回答by Davit Siradeghyan

Use the Abstract Factory pattern when a system should be independent of how its products are created, composed, and represented. a system should be configured with one of multiple families of products. a family of related product objects is designed to be used together, and you need to enforce this constraint. you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

当系统应该独立于其产品的创建、组合和表示方式时,请使用抽象工厂模式。系统应配置多个系列产品之一。一系列相关的产品对象旨在一起使用,您需要强制执行此约束。你想提供一个产品的类库,你只想显示它们的接口,而不是它们的实现。

回答by Penuel

I think its when you want your application to be loosely coupled and extensible in future without coding changes.

我认为这是当您希望您的应用程序在未来无需更改编码的情况下松散耦合和可扩展的时候。

I have written a post on blog as to why i choose the factory pattern in my project and may be it can give you more insight. The example is in PHP but i think its applicable in general to all languages.

我在博客上写了一篇关于为什么我在我的项目中选择工厂模式的帖子,也许它可以让你更深入地了解。该示例使用 PHP,但我认为它通常适用于所有语言。

http://www.mixedwaves.com/2009/02/implementing-factory-design-pattern/

http://www.mixedwaves.com/2009/02/implementing-factory-design-pattern/

回答by Dhrumil Shah

I am using Factory pattens when

我在使用工厂模式时

  1. When a class does not know which class of objects it must create.

  2. A class specifies its sub-classes to specify which objects to create.

  3. In programmer's language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.

  1. 当一个类不知道它必须创建哪个类的对象时。

  2. 类指定其子类以指定要创建的对象。

  3. 在程序员的语言(非常原始的形式)中,您可以使用工厂模式,您必须根据提供的数据创建任何一个子类的对象。

回答by Nitin

Factory method pattern can be used when there is a need to generate objects that belong to specific family. Along side this requirement, you also want to keep the decisions made regarding object instantiation in one place.

当需要生成属于特定系列的对象时,可以使用工厂方法模式。除了这一要求,您还希望将有关对象实例化的决定保留在一个地方。

Please refer the following link for more details.

请参阅以下链接了解更多详情。

http://xeon2k.wordpress.com/2010/11/27/factory-method-pattern/

http://xeon2k.wordpress.com/2010/11/27/factory-method-pattern/

回答by Kevin

Use a factory method (not abstract factory) when you want to reuse common functionality with different components.

当您想对不同组件重用公共功能时,请使用工厂方法(而不是抽象工厂)。

Example:Imagine you have an M16 rifle. Something like this:

示例:假设您有一支 M16 步枪。像这样的东西:

public class M16
{
    private Scope scope = new StandardScope();
    private SecondaryWeapon secondary = new Bayonet();
    private Camouflage camo = new DesertCamo();

    public double getMass()
    {
        // Add the mass of the gun to the mass of all the attachments.
    }

    public Point2D shootAtTarget(Point2D targetPosition)
    {
        // Very complicated calculation taking account of lots of variables such as
        // scope accuracy and gun weight.
    }
}

You may be satisfied with it for a while, thinking that you wont want to change anything. But then you have to do a secret nightime stealth mission in the jungle, and you realise that your attachments are completely inappropriate. You really need a NightVision scope, JungleCamo and a GrenadeLauncher secondary weapon. You will have to copy past the code from your original M16......not good extensibility.....Factory Method to the rescue!

您可能会对此感到满意一段时间,认为您不会想要改变任何东西。但是后来你不得不在丛林中执行一个秘密的夜间隐身任务,你发现你的附件完全不合适。你真的需要夜视镜、丛林迷彩和榴弹发射器辅助武器。您将不得不复制原始 M16 中的代码......扩展性不佳......工厂方法来救援!

Rewrite your M16 class:

重写你的 M16 类:

public abstract class M16
{
    private Scope scope = getScope();
    private SecondaryWeapon secondary = getSecondaryWeapon();
    private Camouflage camo = getCamouflage();

    public double getMass()
    {
        // Add the mass of the gun to the mass of all the attachments.
    }

    public Point2D shootAtTarget(Point2D targetPosition)
    {
        // Very complicated calculation taking account of lots of variables such as
        // scope accuracy and gun weight.
    }

    // Don't have to be abstract if you want to have defaults.
    protected abstract Scope getScope();
    protected abstract SecondaryWeapon getSecondaryWeapon();
    protected abstract Camouflage getCamouflage();
}


//Then, your new JungleM16 can be created with hardly any effort (and importantly, no code //copying):

public class JungleM16 : M16
{
    public Scope getScope()
    {
        return new NightVisionScope();
    }

    public SecondaryWeapon getSecondaryWeapon()
    {
        return new GrenadeLauncher();
    }

    public Camouflage getCamouflage()
    {
        return new JungleCamo();
    }
}

Main idea? Customise and swap out composing objects while keeping common functionality.

大意?自定义和交换组合对象,同时保持通用功能。

An actually useful place to use it: You have just designed a really cool GUI, and it has a really complicated layout. It would be a real pain to have to layout everything again if you wanted to have different widgets. So.....use a factory method to create the widgets. Then, if you change your mind (or someone else want to use your class, but use different components) you can just subclass the GUI and override the factory methods.

一个真正有用的地方:你刚刚设计了一个非常酷的 GUI,它有一个非常复杂的布局。如果您想拥有不同的小部件,那么必须重新布局所有内容将是一件非常痛苦的事情。所以.....使用工厂方法来创建小部件。然后,如果您改变主意(或其他人想使用您的类,但使用不同的组件),您可以只对 GUI 进行子类化并覆盖工厂方法。