Reputation: 675
I am designing a simple security system, which has sensors, that sense the sound, motion or smoke and then sound the alarm and switch on and off the lights according to what was sensed. Using OOP concepts here; I ran into a situation where I am establishing HAS-A relation and runtime polymorphism at the same time(where I place a child class reference into the object of parent class). I want to know whether it is a safe choice or not? I have a class named Light which has 3 subclasses RegLight, GreenLight and NormalLight
public class SecuritySystem {
public void switchOnOffLights(int sensorNumber){
Light light;
if (sensorNumber == 1){
light = new NormalLight();
light.lightFunctionality();
} else if (sensorNumber == 2){
light = new RedLight();
light.lightFunctionality();
}else if (sensorNumber == 3){
light = new GreenLight();
light.lightFunctionality();
}
}
}// end Security System class
Upvotes: 0
Views: 37
Reputation: 38094
From the first glance, all your Light
classes have the same behaviour or the same methods. So it is possible to avoid always editing method switchOnOffLights()
if you will add new sensorNumber by using factory and using inheritance.
So let's see the code via C#. Code is simple and I made a comments how to convert it to Java.
Here you need enums of light types:
public enum LightType
{
Normal,
Red,
Green
}
Then this is our abstract class:
public abstract class Light
{
public abstract void LightFunctionality();
}
And its concrete implementations:
public class NormalLight : Light // Use "extends" in Java instead of ":"
{
public override void LightFunctionality()
{
throw new NotImplementedException();
}
}
public class RedLight : Light // Use "extends" in Java instead of ":"
{
public override void LightFunctionality()
{
throw new NotImplementedException();
}
}
public class GreenLight : Light // Use "extends" in Java instead of ":"
{
public override void LightFunctionality()
{
throw new NotImplementedException();
}
}
And our factory:
public class LightFactory
{
public Dictionary<LightType, Light> LightByType = new
Dictionary<LightType, Light>() // HashTable in Java
{
{ LightType.Normal, new NormalLight() },
{ LightType.Red, new RedLight() },
{ LightType.Green, new GreenLight() }
};
}
And then you can create your objects like this:
public void SwitchOnOffLights(LightType lightType)
{
Light light;
LightFactory lightFactory = new LightFactory();
light = lightFactory.LightByType[lightType];
light.LightFunctionality();
}
Upvotes: 1