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?

有帮助吗?

解决方案

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?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top