其他分享
首页 > 其他分享> > CodeGo.net>如何用依赖注入替换工厂模式

CodeGo.net>如何用依赖注入替换工厂模式

作者:互联网

我有以下情况:必须根据每个对象的特定属性(将属性定义为Enum)将对象集合发送给不同的第三方.我打算使用如下所示的Factory模式来实现此目的.

可以将其重构为使用依赖项注入吗?

public class ServiceA: IThirdParty
{
    public void Send(Ticket objectToBeSent)
    {
        // a call to the third party is made to send the ticket
    }
}

public class ServiceB: IThirdParty
{
    public void Send(Ticket objectToBeSent)
    {
        // a call to the third party is made to send the ticket
    }
}

public interface IThirdParty
{
    void Send(Ticket objectToBeSent);
}

public static class ThirdPartyFactory
{
    public static void SendIncident(Ticket objectToBeSent)
    {
        IThirdParty thirdPartyService = GetThirdPartyService(objectToBeSent.ThirdPartyId);
        thirdPartyService.Send(objectToBeSent);
    }

    private static IThirdParty GetThirdPartyService(ThirdParty thirdParty)
    {
        switch (thirdParty)
        {
            case ThirdParty.AAA:
                return new ServiceA();

            default:
                return new ServiceB();
        }
    }
}

解决方法:

是的,可以对其进行重构-将服务注入SendIncident或它的类.

标签:dependency-injection,factory-pattern,c,net
来源: https://codeday.me/bug/20191030/1971462.html