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

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

问题描述

解决方案

我喜欢思考关于我的课程是人的设计模式,模式是人们彼此交谈的方式。



所以,对我来说,工厂模式是像招聘机构。你有一个需要可变数量的工作人员的人。这个人可能知道他们所雇用的人所需要的一些信息,但是就是这样。



所以,当他们需要一个新员工的时候,他们会打电话给招聘机构并告诉他们他们需要什么现在,为了实际使用某人,你需要知道很多东西 - 好处,资格验证等等。但是,招聘人员不需要知道这些 - 招聘机构处理所有那么。



以同样的方式,使用Factory允许消费者创建新对象,而不必知道如何创建它们的细节,或者它们的依赖关系 - 他们只需要提供他们实际想要的信息。

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

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

所以,现在ThingFactory的消费者可以得到事情,而不必知道Thing的依赖,除了来自消费者的字符串数据。


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);
    }
}

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天全站免登陆