mercredi 31 janvier 2018

multilevel inheritance - use without casting

Below is the class structure to check the Rule.

RuleBase, RuleResultBase, and IDisplayType are the base classes and interfaces.

RuleTypeA, RuleResultTypeA, and DisplayTypeA are always used together.

When implementing the Run function of RuleTypeA, always use Casting to use DisplayType. I think something is uncomfortable structure. Is not there a good way?

public interface IDisplayType
{
}

public class DisplayTypeA : IDisplayType
{
}

public class DisplayTypeB: IDisplayType
{
}

public abstract class RuleBase
{
    public RuleResultBase Result { get; set; }

    public abstract void Run();
}

public class RuleResultBase
{
    public IDisplayType DisplayType { get; set; }
}

public class RuleResultTypeA: RuleResultBase
{
    public RuleResultTypeA()
    {
        DisplayType = new DisplayTypeA();
    }
}

public class RuleTypeA : RuleBase
{
    public override void Run()
    {
        base.Result = new RuleResultTypeA();

        /// Should I always use this Casting?
        var displayType = base.Result.DisplayType as DisplayTypeA;            
    }
}

public Main()
{
    var rules = new List<RuleTypeA>();
    rules.Add(new RuleTypeA());
    rules.Add(new RuleTypeA());
    foreach(var rule in rules)
    {
        rule.Run();
    }
}

In addition, I've thought of using Generic, but in actual implementation, RuleBase has many variables besides DisplayType. So it does not look good.

public abstract class RuleBase<TDisplayType>
{
    public RuleResultBase<TDisplayType> Result { get; set; }

    public abstract void Run();
}

public class RuleResultBase<TDisplayType>
{
    public TDisplayType DisplayType { get; set; }
}

public class RuleResultTypeA: RuleResultBase<DisplayTypeA>
{
    public RuleResultTypeA()
    {
        DisplayType = new DisplayTypeA();
    }
}

Aucun commentaire:

Enregistrer un commentaire