C#工厂模式和IoC的区别

发布于 2024-10-14 03:09:28 字数 230 浏览 4 评论 0原文

可能的重复:
依赖注入与工厂模式

有人可以解释一下(用简单的例子)两者之间的区别工厂模式和控制反转模式。最好使用.NET2.0

Possible Duplicate:
Dependency Injection vs Factory Pattern

Can someone please explain (with SIMPLE examples) of the difference between the factory pattern and Inversion of Control pattern. Preferably using .NET2.0

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月静好 2024-10-21 03:09:28

工厂模式是关于获取对类型的引用,因此在代码中的某个位置您将调用工厂来解决某些问题。

控制反转模式意味着您通常会使用 Ioc 容器来为您解决依赖关系。这可能与工厂类似,或者更常见的是,您将使用依赖项注入将依赖项解析到构造函数或设置器中。

The factory pattern is about getting the reference to a type, so somewhere in your code you would be calling into a factory to resolve something.

The Inversion of control pattern means that you would typically use an Ioc container to resolve dependencies for you. This could be in a similar way to a factory, or more typically you would use dependency injection to resolve the dependencies into the constructor or setters.

因为看清所以看轻 2024-10-21 03:09:28

工厂模式:
需要引用服务的对象,应该知道创建服务的工厂:

public class BLLObject 
{
    public IDal DalInstance { get; set; }

    public BLLObject()
    {
        DalInstance = DalFactory.CreateSqlServerDal();
    }
}

Ioc 模式(或依赖注入):

对象只需要声明它对服务的需要,使用任何Ioc 模式的各个方面(构造函数、设置器或接口...等)
容器会尝试满足这个需求:

public class BLLObject 
{
    public IDal DalInstance { get; set; }

    public BLLObject(IDal _dalInstance)
    {
        DalInstance = _dalInstance;
    }
}

这意味着在工厂模式中,对象决定使用哪种创建方法(通过选择特定的具体工厂),但在 Ioc 模式中,则由容器来选择。

当然这不是唯一的尊重,但这是我暂时的想法。
如果我错了请纠正我?

The factory pattern:
the object which needs a reference to a service, should know about the factory that creates the Service:

public class BLLObject 
{
    public IDal DalInstance { get; set; }

    public BLLObject()
    {
        DalInstance = DalFactory.CreateSqlServerDal();
    }
}

The Ioc Pattern (or Dependency Injection) :

the object only needs to declare its need to the service, using any aspects of the Ioc Pattern (Constructor, setter, or interface ... etc)
and the container will try to fulfill this need:

public class BLLObject 
{
    public IDal DalInstance { get; set; }

    public BLLObject(IDal _dalInstance)
    {
        DalInstance = _dalInstance;
    }
}

which means that in the factory pattern, the object decides which creation method (by choosing a specific concrete factory) to use, but the in the Ioc pattern, it is up to the container to choose.

of course this is not the only deference, but this is what is in my mind for the time being.
correct me please if I'm wrong ?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文