Create an instance of an interface child class

I have an interface and 3 classes that produce it, but how to use 1 variable for each type?

  public interface IBuilder<T> where T: System.IConvertible{}

  public class SimpleBuilder :  IBuilder<SimpleCollagePatterns>{}

  public class CreativeBuilder : IBuilder<CreativeCollagePatterns>{}

  public class ShapeBuilder : IBuilder<ShapeCollagePatterns>{}

And I need to instantiate the class when necessary

I have a variable IBuilder<IConvertible> currentBuilder, but I can not instantiate anyBuilder

this.currentBuilder = new SimpleBuilder(); //Doesn`t work

Only if I change IBuilder<IConvertible> currentBuilderto IBuilder<SimpleCollagePatterns> currentBuilderor another type can I create this type of Builder, but I need the rage to create any type

+4
source share
5 answers

. , . . , IBuilder currentBuilder IBuilder currentBuilder - SimpleBuilder. .

0

, IS, , , :

if (this.currentBuilder - SimpleBuilder) { }

0

, IBuilder, . https://msdn.microsoft.com/en-us/library/dd997386(v=vs.110).aspx

public interface IBuilder<out T>

0

, , , out .

public interface IBuilder<out T> where T: System.IConvertible{}

IBuilder<IConvertible> , . SimpleBuilder, , , , , .

IBuilder - .

SO, . Contra-variance , . https://msdn.microsoft.com/en-us/library/mt654055.aspx.

0

, SimpleCollagePatterns , ( ShapeBuilder), .

, .

:

public interface IBuilder {
    void Build();
}

public interface IBuilder<T> : IBuilder {
    T BuildParameter {get;}
}

. BuildParameter BuildCollagePattern

:

public class SpecificBuilder : IBuilder<Int32> {
    // The specific constructor
    public SpecificBuilder(int param) { BuildParameter = param; }

    // Implement from IBuilder
    public void Build() {
        System.Console.WriteLine("Building with Int32: " + BuildParameter);
    }

    // Implement from IBuilder<T>
    public Int32 BuildParameter {get; private set;}
}

IBuilder<T> IBuilder

public class Program {
    public static void Main() {
        SpecificBuilder builder = new SpecificBuilder(42);

        // SpecificBuilder implements IBuilder<Int32>
        // Build accepts any IBuilder
        // So this is legal:
        Build(builder);
    }

    //
    // Note this method accepts anything that inherits from IBuilder
    // 
    public static void Build(IBuilder builder) {

        builder.Build();

        // If you'd need access to the BuildParameter of IBuilder<T>
        // then this pattern fails you here.
        // Unless of course you want to check for types and cast
    }
}

: , , IBuilder<T>, . .

But you can design many things this way and support extensibility. I use this template to implement image filters, and yours BuildCollagePatterncan be very realistic with this design pattern.

0
source

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


All Articles