Reputation: 19
Assume we have a collection of vehicles. The vehicles may be a bicycle, motorbike or car.
Now every car in this collection should have its windows cleaned.
There is a WindowCleaner that receives this collection of vehicles. How can he tell which vehicle needs its windows cleaned? I see that if I differentiate between the vehicle subtypes in the WindowCleaner I will violate the open-closed principle.
How else could one do this? Introduce an abstract bool property NeedsWindowsCleaned and then cast to the subtype? This looks to me like type introspection in disguise.
Upvotes: 0
Views: 83
Reputation: 250
using System;
using System.Collections.Generic;
namespace Dirty
{
class Program
{
static void Main()
{
var vehicles = new List<Vehicle>();
var bike = new Bicycle();
var motorbike = new Motorbike();
var car = new Car();
vehicles.Add(bike);
vehicles.Add(motorbike);
vehicles.Add(car);
foreach (var v in vehicles)
{
if (v.CleanWindows())
{
Console.WriteLine("{0}", v);
}
}
Console.ReadKey();
}
}
class Vehicle
{
public virtual bool CleanWindows()
{
return false;
}
}
class Bicycle : Vehicle
{
}
class Motorbike : Vehicle
{
}
class Car : Vehicle
{
public override bool CleanWindows()
{
return true;
}
}
}
I think this might do what you are after - all the classes inherit from "Vehicle" & can optionally override the virtual "CleanWindows" method ... if they don't they get the default "false"
I hope I haven't misunderstood - I am new to all this :)
Upvotes: 1