jeudi 17 août 2017

SOLID principles in C# - open/closed principle

I have below problem statement:

"Building a smartDevice which can act as Oven as well as refrigerator.

Oven Features

• The device should be able to show current time

• the Oven should show message “HEAT!!!”

Refrigerator Features

• The device should be able to show current time

• On Press of stop should show “Switched Off”

Part II

We need an enhancement, now the Refrigerator can also be used as oven, so add a toggle button to select appliance type • If button type id "Oven button” then the message “HEAT !!!” should be shown on Oven.

• If button type “Refrigerator button” then the message “Refrigerator HEAT !!!” should be shown on Refrigerator.

I have written the implementation like this:

class Program
{
    static void Main(string[] args)
    {
        Oven o = new Oven();
        Refrigerator r = new Refrigerator(true);

        Driver d = new Driver(o);
        d.ShowCurrenTime();
        Console.ReadLine();
    }
}

public class Driver
{
    private IOven instance;

    public Driver(IOven inst)
    {
        instance = inst;
    }

    public void ShowCurrenTime()
    {
        instance.ShowCurrenTime();
    }

    public void Button()
    {
        instance.Button();
    }
}

public interface IOven
{
    void ShowCurrenTime();
    void Button();
    void Toggle();
}

public class Oven : IOven
{
    public void ShowCurrenTime()
    {
        Console.WriteLine(DateTime.Now);
    }

    public void Button()
    {
        Console.WriteLine("Heat");
    }

    public void Toggle()
    {
        Console.WriteLine("Refrigerator HEAT !!!");
    }
}

public class Refrigerator : IOven
{
    public bool stop = false;

    public Refrigerator(bool Stop)
    {
        stop = Stop;
    }

    public void ShowCurrenTime()
    {
        Console.WriteLine(DateTime.Now);
    }

    public void Button()
    {
        if(stop == true)
        {
            Console.WriteLine("Switched Off");
        }
    }

    public void Toggle()
    {
        Console.WriteLine("HEAT !!!");
    }
}

In this program I have made use of Interfaces, dependency Injection. But I am not able to solve the Part 2 of the problem statement exactly .

How do I configure using a toggle button?

Aucun commentaire:

Enregistrer un commentaire