3

次の状況があります。オブジェクトのコレクションを、各オブジェクトの特定のプロパティに基づいて異なるサード パーティに送信する必要があります (プロパティは 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();
        }
    }
}
4

5 に答える 5

1

As far as I can tell, this question is about run-time selection or mapping of one of several candidate Strategies - in this case selecting the correct IThirdParty implementation based on a ThirdParty enum value.

There are at least three ways to do this in, and none of them require a factory:

My personal preference is the Partial Type Name Role Hint.

于 2014-04-02T05:28:09.507 に答える