是否测试接口实现良好的设计?

时间:2014-01-06 11:56:11

标签: c#

我有一个相当普遍的问题。设计好几个类可能实现一个公共接口但没有其他共同之处并测试接口是否被实现以执行某些操作是好还是坏?

示例:可以使用Builder的子类实例在外部配置Something对象。其中一些子类有一个特殊的BuildCommand方法,有些则没有。如果当前Something没有BuildCommand方法,则Builder应使用BuildCommand类中定义的默认Target方法。

我不太确定我的解决方案是否会被认为是好的或坏的设计。我很感激你的意见。

非常感谢, 费边

public interface ICommandBuilder
{
    ICommand BuildCommand();
}

public class Something1 : Something
{
    /* ... */
}
public class Something2 : Something, ICommandBuilder
{
    /* ... */
}

public class Target : ICommandBuilder
{
    /* ... */
}

public class Builder
{
    public Something Something { get; set; }

    public Target CreateTarget()
    {
        var target = new Target();

        /* Some code to configure target */

        var commandBuilder = (Something as ICommandBuilder) ?? Target;
        target.AddCommand(commandBuilder.BuildCommand());

        return target;
    }
}

1 个答案:

答案 0 :(得分:0)

如果您需要ICommandBuilder,请使用ICommandBuilder类型的属性,这样可以明确您的依赖关系:

public class TargetBuilder
{
    public ICommandBuilder CommandBuilder { get; set; }
    public Something Something { get; set; }

    public Target CreateTarget()
    {
        var target = new Target();    
        /* Some code to configure target */

        var commandBuilder = CommandBuilder ?? target;
        target.AddCommand(commandBuilder.BuildCommand());

        return target;
    }
}

您可以将同一对象实例分配给SomethingCommandBuilder属性。对于两个不同的目的,有两个不同的属性对我来说很清楚。检查Something是否实施ICommandBuilder没有隐藏功能

您甚至可以创建构造函数,它将接受同时实现SomethingICommandBuilder的类型,以简化两个属性的分配:

public TargetBuilder()
{
}

public TargetBuilder(Something2 something2)
   : this(something2, something2)
{
}

public TargetBuilder(Something something, ICommandBuilder commandBuilder)
{
    Something = something;
    CommandBuilder = commandBuilder;
}