1

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?

Doug Peters
  • 529
  • 2
  • 8
  • 17

1 Answers1

1

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?

Community
  • 1
  • 1
Karl Kieninger
  • 8,841
  • 2
  • 33
  • 49
  • Thanks for your comment. What if all three inheritable interfaces also apply to a motorbike, which is not essentially a car, but both are vehicles. But think of static crane, it has a motor (to lift the freight), it has a break (to stop the lifting at the desired height) and also can have an alarm for when it remains unattended, but it's not a vehicle (as it is mounted to the ground) and let's say I need to be able to disable some of this inherited functionality at run-time, how can I do it? – Doug Peters Apr 09 '14 at 01:18
  • 1
    Your motorbike would still _have a_ motor, _have a_ brake, _have a_ alarm. If you have something that should operate differently at rune-time, provide a different implementation. Consider something like `crane.Alarm = new NoAlarm()` – jdphenix Apr 09 '14 at 01:21
  • What @jdphenix said. Inheritance says you crane is so you can't remove the motor if you part it for scrape or whatever. You could certainly add an Enable (or Disable) property to your interfaces, but will bloat them and not really represent the motor or alarm being removed. – Karl Kieninger Apr 09 '14 at 01:26