Without LSP:Example, we are creating different robots, Kawasaki, Yaskawa, and ABBRobots all inheriting IRobots and have methods like Connect(), Operate() , Move(). Later say some new functionality in ABBRobots like ReportFaultData() is introduced, so we need to added ReportFaultData() in interface and other robots should do " throw NotSupportedException("Reporting fault data is not supported");" , this leads to compile time error or we need to do nothing, and so we need to change other classes.
With LPS:Instead we will create new interface ISupportsFaultDataReporting and add the new ReportFaultData() and inherit only for ABBRobots
public class ABBRobots : IRobots, ISupportsFaultDataReporting
{
}
public class Program
{
public static void Main()
{
List robots = new List{new Kawasaki(),new Yaskawa(),new ABBRobots()};
foreach (var robot in robots)
{
robot.Move();
if (robot is ISupportsFaultDataReporting faultDataReportingRobot)
{
faultDataReportingRobot.Report();
}
}
}
}
Without LSP:
Why the name substitution - The idea is that you should be able to substitute the base class with the derived class without breaking the functionality.
// Substituting base class with dereived class
Shape shape = new Rectangle(5, 10);
Without LSP:
Example, we are creating different robots, Kawasaki, Yaskawa, and ABBRobots all inheriting IRobots and have methods like Connect(), Operate() , Move(). Later say some new functionality in ABBRobots like ReportFaultData() is introduced, so we need to added ReportFaultData() in interface and other robots should do " throw NotSupportedException("Reporting fault data is not supported");" , this leads to compile time error or we need to do nothing, and so we need to change other classes.
With LPS:
Instead we will create new interface ISupportsFaultDataReporting and add the new ReportFaultData() and inherit only for ABBRobots
public class ABBRobots : IRobots, ISupportsFaultDataReporting
{
}
public class Program
{
public static void Main()
{
List robots = new List{new Kawasaki(),new Yaskawa(),new ABBRobots()};
foreach (var robot in robots)
{
robot.Move();
if (robot is ISupportsFaultDataReporting faultDataReportingRobot)
{
faultDataReportingRobot.Report();
}
}
}
}
Without LSP:
Why the name substitution - The idea is that you should be able to substitute the base class with the derived class without breaking the functionality.
// Substituting base class with dereived class
Shape shape = new Rectangle(5, 10);
No comments:
Post a Comment