繁体   English   中英

OOP设计设置器与方法中的传递参数

[英]OOP Design setter vs passing parameter in method

在这种情况下,我对良好的OOP设计有疑问:

这个例子是不真实的。 但是我不能给你真正的例子,因为它是私有代码。 但是示例概念完全相同。

想象一下,我有一个存储字符串列表的类,并且有一个名为ThereIsString(string mystring)的方法。

我返回的是true还是false取决于我对该字符串“相关”到其中一个字符串的计算是否为listOfString。 (这是私有算法)

例:

public class StringBagAlgorithm()
{
    List<string> listofString = new List<string>();

    public boolean ComputeString(string myString)
    {
        return true or false depending on the computation with the list of strings;
    }
}

好。 字符串列表存储在另一个名为ListOfStrings的类中,该类具有对StringBagAlgorithm的引用,因此:

public class ListOfStrings()
{
    List<string> listofString = new List<string>();
    List<string> MySecondListofString = new List<string>();
    StringBagAlgorithm _bagAlgorithm

    public ListOfStrings(StringBagAlgorithm bagAlgorithm)
    {
        this._bagAlgorithm = bagAlgorithm;
    }

    public void ComputeSecondList()
    {
       for (int i=0; i<MySecondListofString; i++ )
          _bagAlgorithm.ComputeString(MySecondListofString[i]);
    }
}

我的问题是将listofString传递给StringBagAlgorithm的最佳方法是什么。 例如,通过在for循环中执行此操作:

_bagAlgorithm.ComputeString(MySecondListofString [I],listofString);

或者在执行for循环之前使用setter进行操作。 还是其他选择?

想知道哪种是用于松耦合和单元测试的最佳OO设计。 另外我猜想,通过一次使用setter而不在每个调用中传递列表,性能会更好,但设计会更糟吗?

它必须是这样的:

public class StringBagAlgorithm
{
    public List<string> ListofString { get; set; }

    public bool ComputeString(string myString)
    {
        //return true or false depending on the computation with the list of strings;
        return true;
    }
}

public class StringsComputer
{
    public List<string> FirstList { get; set; }
    public List<string> SecoundList { get; set; }
    public StringBagAlgorithm BagAlgorithm { get; set; }

    public StringsComputer(StringBagAlgorithm bagAlgorithm, List<string> listA, List<string> listB)
    {
        BagAlgorithm = bagAlgorithm;
        FirstList = listA;
        SecoundList = listB;
    }

    public StringsComputer()
    {
    }

    public void ComputeSecondList()
    {
        if(BagAlgorithm != null)
        {
           for (int i = 0; i < SecoundList.Count; i++)
               BagAlgorithm.ComputeString(SecoundList[i]);
        }
    }
}

public class program
{
    public static void Main()
    {
        List<string> listA = new List<string>() { "A", "B", "C", "D" };
        List<string> listB = new List<string>() { "E", "F", "C", "H" };
        StringBagAlgorithm sba = new StringBagAlgorithm();

        StringsComputer sc = new StringsComputer() {
            FirstList = listA,
            SecoundList = listB,
            BagAlgorithm = sba
        };

        sc.ComputeSecondList();
    }
}

调用类ListOfStrings的最著名错误! class应该是它的类型之一,如果需要很多,可以使用List<MyNewClass> 了解有关SRP和接口/抽象的信息,并尝试实现它们以获得更好的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM