mardi 28 avril 2015

Whats the point of the interface?

I have this code where I am using the proxy pattern:

static void Main() {

    Driver d = new Driver(16);
    Driver d2 = new Driver(26);

    ICar p = new ProxyCar(d);
    ICar p2 = new ProxyCar(d2);

    Console.WriteLine(p.DriveCar());
    Console.WriteLine(p2.DriveCar());
}

}

interface ICar
{
    string DriveCar();

}

public class ProxyCar : ICar
{
    Driver driver;
    ICar realCar;
    public ProxyCar(Driver driver)
    {
        this.driver = driver;
        realCar = new Car();
    }



    public string DriveCar()
    {
        string result;

        if (driver.Age <= 16)
            result= "Sorry, the driver is too young to drive.";
        else
            result = realCar.DriveCar();

        return result;
    }
}


public class Car:ICar
{
    public string DriveCar()
    {
        return "Driving car!";
    }


}

public class Driver
{
    private int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    public Driver(int age)
    {
        _age = age;
    }
}

But I cant see the reason to use this Interface ICar. I could just use the code like this without the interface and it will work just fine:

static void Main() {

    Driver d = new Driver(16);
    Driver d2 = new Driver(26);

    ProxyCar p = new ProxyCar(d);
    ProxyCar p2 = new ProxyCar(d2);

    Console.WriteLine(p.DriveCar());
    Console.WriteLine(p2.DriveCar());
}

}

public class ProxyCar 
{
    Driver driver;
    Car realCar;
    public ProxyCar(Driver driver)
    {
        this.driver = driver;
        realCar = new Car();
    }



    public string DriveCar()
    {
        string result;

        if (driver.Age <= 16)
            result= "Sorry, the driver is too young to drive.";
        else
            result = realCar.DriveCar();

        return result;
    }
}


public class Car
{
    public string DriveCar()
    {
        return "Driving car!";
    }


}

public class Driver
{
    private int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    public Driver(int age)
    {
        _age = age;
    }
}

So why should I use the ICar interface?

Aucun commentaire:

Enregistrer un commentaire