Question

Let's say I have a cars game and we're in the car set-up garage. The default model comes prefactored with these accessories:

public class MyCar : IMotor, IBrakes, IAlarm
{
   public void Run(){...};
   public void Stop(){...};
   public void ProtectFromThieft(){...};
}

public interface IMotor
{
   void Run();
}

public interface IBrakes
{
   void Stop();
}

public interface IAlarm
{
   void ProtectFromThieft();
}

The game player has already instantiated a MyCar object and then he decides to sell the alarm back to the garage to get some cash.

How do I disable IAlarm's functionality from the concrete MyCar implemenation at run-time?

Was it helpful?

Solution

Use composition here instead of inheritance. You car is a motor, is an alarm, and is brakes, when instead it should have them. This decoupling makes what you want to do far easier.

See Prefer composition over inheritance?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top