Confusion with interfaces, factories, and inversion of control

Using interfaces is a very simple way to remove dependencies, but what happens when one of your classes needs a method not defined by the interface? If you use constructor injection or factory, how do you access this additional method without casting? Is it possible?

Here is a factory example with this problem. Am I trying to do something impossible? Thank you for your help.

interface IFoo {
    int X { get; set; }
    int Y { get; set; }
}

public class A : IFoo {
    int X { get; set; }
    int Y { get; set; }
}

public class B : IFoo {
    int X { get; set; }
    int Y { get; set; }
    int Z { get; set; }
}

public static class FooFactory {
    public static IFoo GetFoo(string AorB) {
        IFoo result = null;
        switch (AorB) {
            case "A":
                result = new A();
                break;
            case "B":
                result = new B();
                break;
        }
        return result;
    }
}

public class FooContainer {
    private IFoo foo;

    public FooContainer(IFoo foo) {
        this.foo = foo;
    }

    /* What methods would you define here. I'm new to IoC. */
}

public class Main(...) {
    int x,y,z;
    IFoo fooA = FooFactory.GetFoo("A");
    x = foo.X;
    y = foo.Y;

    IFoo fooB = FooFactory.GetFoo("B");
    x = foo.X;
    y = foo.Y;
    z = foo.Z; /* Does not compile */
    z = ((B)foo).Z; /* Compiles, but adds unwanted dependency */
}
+3
source share
3 answers

When you are faced with the need to lower an object, this is usually a sign that the API may be better.

. , . , ( CQS), - . .

, IFoo X Y, :

public interface IFoo
{
    void DoStuff();

    void DoSomethingElse(string bar);

    void DoIt(DateTime now);
}

, ( X, Y Z), .

, .

+1

. , . , - .

, / / , , . , , , -, , .

, IContact, , , , . SendChristmasCard, IContact, IContact. , select Case obj.GetType().ToString, , , :

  • , , , Customer . ( , A B.)
  • IContact , SendChristmasCard, , . , IContact, -. ( A B, .)

, , , , , , . , , "" , . , , . SendChristmasCard, , ; IContact factory - , , , , , SendChristmassCard (IContact Contact), , " " " " .. , , .

Decorator Pattern, .

+6

, , Factory. , , ... (, ).

.

, , ... , . - Factory , , .

+1

Source: https://habr.com/ru/post/1734916/


All Articles