mercredi 11 novembre 2020

Simple state design pattern for a visual studio windows form

I'm moving a button component on the form up and down using if-else clauses at the moment.

public void btnUp_Click(object sender, EventArgs e)
{
        if (lift_status == 0)
        {
            timer1.Start();
        }
}

and

public void btnDown_Click(object sender, EventArgs e)
{
        if (lift_status == 1) 
        { 
            timer2.Start();
        }
}

The code in the timers are:

private void timer1_Tick(object sender, EventArgs e)
    {
        if (Elevater.Location.Y > 80)
        {
            Elevater.Top -= 10;
        }
        else
        {
            timer1.Stop();

            lblFloorLevel.Text = "Floor 1";
            lift_status = 1;
            // changing the status                       
            LstElevaterEvents.Items.Add(DateTime.Now.ToString("h:mm:ss tt") + " Lift went up");

            DataRow newRow = ds.Tables[0].NewRow();
            newRow["Events_In_Elevater"] = DateTime.Now.ToString("h:mm:ss tt") + " Lift went up";
            //add the new DataRow to DataTable 
            ds.Tables[0].Rows.Add(newRow);
        }
    }

And

if (Elevater.Location.Y < 200)
        {
            Elevater.Top += 10;
        }
        else
        {
            lblFloorLevel.Text = "Floor 0";
            lift_status = 0;
            LstElevaterEvents.Items.Add(DateTime.Now.ToString("h:mm:ss tt") + " Lift went down");
            DataRow newRow = ds.Tables[0].NewRow();
            newRow["Events_In_Elevater"] = DateTime.Now.ToString("h:mm:ss tt") + " Lift went down";
            //add the new DataRow to DataTable 
            ds.Tables[0].Rows.Add(newRow);
            timer2.Stop();
        }

But for my assignment, I need to move the button using the state design pattern instead of using an if-else statement and I can't implement it.

Can I override the btn_click event handler? How do I create a context class and link it to the form? How do I link the overridden method to the timer method that I have? I'm all kinds of confused.

Simple code for the context class and an example state class would be fantastic, THANKS!!

Aucun commentaire:

Enregistrer un commentaire