工厂模式.什么时候使用工厂方法? [英] Factory Pattern. When to use factory methods?

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

问题描述

什么时候在对象中使用工厂方法而不是工厂类是个好主意?

When is it a good idea to use factory methods within an object instead of a Factory class?

推荐答案

我喜欢从我的班级是人"的角度来思考设计模式,而模式是人们相互交谈的方式.

I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.

所以,对我来说,工厂模式就像一个招聘机构.你有一个需要可变数量工人的人.这个人可能知道他们需要从他们雇佣的人那里获得的一些信息,但仅此而已.

So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.

因此,当他们需要新员工时,他们会致电招聘机构并告诉他们需要什么.现在,要真正雇用某人,您需要了解很多信息 - 福利、资格验证等.但招聘人员不需要知道任何这些 - 招聘机构会处理所有这些

So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.

同样,使用工厂允许消费者创建新对象,而无需知道它们是如何创建的,或者它们的依赖项是什么——他们只需要提供他们真正想要的信息.

In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.

public interface IThingFactory
{
    Thing GetThing(string theString);
}

public class ThingFactory : IThingFactory
{
    public Thing GetThing(string theString)
    {
        return new Thing(theString, firstDependency, secondDependency);
    }
}

所以,现在 ThingFactory 的消费者可以得到一个 Thing,而无需知道 Thing 的依赖关系,除了来自消费者的字符串数据.

So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.

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

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