Search code examples
c#c#-2.0factory-pattern

How to convert these 4 functions in one?


You can use the enum: enum StatusRouter { Stop = 0, Start, Resume, Suspect };

public bool StartSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Start();
    }
    return false;
}
public bool ResumeSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Resume();
    }
    return false;
}
public bool SuspendSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Suspend();
    }
    return false;
}
public bool StopSelectedRouter()
{
    for (int i = 0; i < m_listPlatforms.Count; i++)
    {
        if (m_listPlatforms[i].IsCheked)
            m_listPlatforms[i].Stop();
    }
    return false;
}

Solution

  • You can pass in a lambda defining the Action you want to do on each element.

    Something like:

    public bool ChangeSelectedRouterState(Action<Router> action) 
    {
        for (int i = 0; i < m_listPlatforms.Count; i++)
        {
            if (m_listPlatforms[i].IsCheked)
                action(m_listPlatforms[i]);
        }
        return false;
    }
    

    Call like this:

    ChangeSelectedRouterState(r => r.Stop());
    

    You will need to substitute the type Router, which I invented for my answer, for your specific type you are working on.