Richter’s substitution principle
- All references to a base class must be able to use objects of its subclasses transparently, that is, subclass objects can replace their parent class objects without the program executing the same.
- In the inheritance system, a subclass can add its own unique methods and implement the abstract methods of the parent class, but cannot override the non-abstract methods of the parent class, otherwise the inheritance relationship is not a correct inheritance relationship.
- The common argument is that wherever base classes are already used, subclasses must be used without introducing errors
Bad design
@interface Car : NSObject @property(nonatomic,copy)NSString *steeringWheel; @property(nonatomic,copy)NSString *tyre; // @property(nonatomic,copy)NSString *cover; (void)run; @implementation Car - (void)run{NSLog(@" this Car can only run 100km/ h "); } @endCopy the code
- Race overrides this method
Implementation Race - (void)run{NSLog(@implementation Race can run 200km/ h); } @endCopy the code
- There’s a problem with that call. According to the Richter’s substitution principle, you can use the car subclass race wherever you use it, but that’s not right
- Where you can only run 100km/ h, you can run 200km/ h
Car *car = [[Car alloc]init];
[car run];
Car *race = [[Race alloc]init];
[race run];
Copy the code
- A good design is for Race to rewrite another method to circumvent the rewrite of the run function.
The actual development
- Although in actual development we would not actually replace the subclass race where CAR is used.
- So to summarize the Richter substitution principle, it’s really just a matter of keeping in mind that when we use inheritance relationships, this subclass can replace its parent class and still run successfully. Richter’s substitution principle is used to restrain the abuse of inheritance relationship.
- Before using inheritance, it is necessary to consider and confirm whether the inheritance relationship is correct, or whether the current inheritance system can support subsequent requirement changes. If not, it is necessary to timely reconstruct and adopt a better design method to design programs.