对象依赖和交互

时间:2015-02-19 20:32:12

标签: c# oop

已编辑:

我正在深入研究OOP的概念,但当我想到我脑子里的想法时,我会在实践中再次感到困惑。

我创建了两个类: 光(代表一个灯泡)

public enum LightState { ON, OFF }

public class Light
{
    private LightState _state;

    public LightState CurrentState
    {
        get { return _state; }
        set { _state = value; }
    }

    public Light() : this(LightState.OFF) { }

    public Light(LightState state)
    {
        CurrentState = state;
    }
}

开关,应该改变灯泡的状态。

public class Switch
{
    private Light _light;

    public LightState State
    {
        get { return _light.CurrentState; }
        private set { _light.CurrentState = value; }
    }

    public Switch(Light light)
    {
        _light = light;
    }

    public void TurnLightsOff()
    {
        if (State.Equals(LightState.OFF))
        {
            PrintState(LightState.OFF);
        }
        else
        {
            State = LightState.OFF;
        }
    }

    public void TurnLightsOn()
    {
        if (State.Equals(LightState.ON))
        {
            PrintState(LightState.ON);
        }
        else
        {
            State = LightState.ON;
        }
    }
}

我没有得到互动部分,是否在我的例子中完成了?

假设我介绍了另一个可以打开/关闭开关的课程Man,那么Man对象应该如何更改Switch的状态?

1 个答案:

答案 0 :(得分:0)

Switch在这里是多余的。将方法放入Light并对其进行操作

public class Light 
{
    ....
    public void Flip()
    {
       if( CurrentState == LightState.ON )
       {
           CurrentState = LightState.OFF;
       } else {
           CurrentState = LightState.ON;
       }   
     }
}

一个人可以采取行动

public class Man
{
    ....
    public void TurnLightOn(Light light)
    {
        light.CurrentState = LightState.ON;
    }
    public void FlipLight(Light light)
    {
        light.Flip();
    }
}