The six principles of design pattern-the Lee's replacement principle

Source: Internet
Author: User
Rys replacement principle

Definition:

All objects that reference the base class must be transparently used.

In layman's terms, as long as the parent class can appear, the Child class will appear, and replacement with the Child class will not produce any errors or exceptions. The user may not need to know whether it is a parent class or a child class.

However, we need to note that the parent class may not be able to adapt to any subclass.

Advantages:

Code sharing reduces the workload of creating classes. each subclass has the methods and attributes of the parent class;

Improve code reusability;

Child classes can be similar to parent classes, but different from parent classes;

Improves code scalability;

Improve the openness of products or projects.

Disadvantages:

Inheritance is invasive. As long as it inherits, it must have all attributes and methods of the parent class;

To reduce code flexibility, subclass must have attributes and methods of the parent class, which adds constraints to the subclass;

The coupling is enhanced. When the constants, variables, and methods of the parent class are modified, the modification of the Child class must be considered.

 

Meaning:

1,Subclass must fully implement the parent class Method

Example:

For example, we know that there are many gun types, and a common function is shooting. In soldier, we added a killenemy () method. This method uses a gun to kill the enemy. The specific gun used depends on the gun used.

Code:

    public abstract class AbstractGun    {        public abstract void Shoot();    }

Class handgun: abstractgun {public override void shoot () {console. writeline ("pistol shot ");}}

Class rifle: abstractgun {public override void shoot () {console. writeline ("Rifle Shot ");}}

Class machinegun: abstractgun {public override void shoot () {console. writeline ("Machine Gun ");}}

Public class soldier {private abstractgun gun; Public extends actgun gun {set {This. gun = value;} get {return gun;} public void killenemy () {console. writeline ("soldiers start shooting"); gun. shoot ();}}

Client:

        static void Main(string[] args)        {            Soldier soldier = new Soldier();            soldier.Gun = new Handgun();            soldier.KillEnemy();        }


Note: When calling other classes in the class, you must use the parent class or interface. If not, it indicates that the class design has violated the LSP principle.

But now there is a toy gun, but we know that the toy gun cannot shoot and kill the enemy like other guns, so the toy gun cannot really implement the shoot method.

Class toygun: abstractgun {public override void shoot () {// This method cannot be implemented because a toy gun cannot shoot or kill people }}

In this case, we find that the service calling class has a problem and the normal business logic cannot run. There are two solutions:

(1) Add judgment in the soldier class. If it is a simulated gun, it will not be used to kill people. This method can solve the problem, but in the program, every time we add a class, all classes related to this parent class must be modified, so that it is not feasible. Therefore, this solution is rejected.

(2) toygun disconnects from inheritance and establishes an independent parent class, which can be associated with abstractgun. The class diagram is as follows:


In general, the above situations often occur in applications, according to the LSP principle:If the subclass cannot fully implement the parent class method, or some methods of the parent class are distorted in the subclass, we recommend that you disconnect the Parent-Child inheritance relationship, inheritance is replaced by dependency, aggregation, and combination.

2,Subclass can have its own personality

Because of this rule, the Rys replacement principle cannot be used in turn. Where a subclass appears, the parent class may not be competent. 3. When overwriting or implementing the parent class method, the input parameters can be enlarged.

The input parameter type of the subclass must be greater than or equal to the parameter of the parent class. When the child class is passed to the caller instead of the parent class, the Child class will never be executed. This is correct. If you want the subclass to be executed, you must override the method of the parent class. However, if, in turn, the subclass parameter type range is smaller than the parent class, then the child class may not exist where the parent class exists. Sub-classes will be executed, which will affect the chaotic business logic, because in actual applications, the parent class is generally the image class, and the sub-class is the implementation class, such a subclass will distort the intent of the parent class.

SoThe preconditions of the method in the subclass must be the same or looser than that of the method overwritten in the parent class.

4. output results can be reduced when override or parent class methods are implemented

For example, if the return value of a method in the parent class is type T and the return value of the same method (overload or overwrite) in the subclass is S, the Rys replacement principle requires s to be less than or equal to T, that is, either S and T are of the same type, or S is a subclass of T.

Summary:

The purpose of adopting the Lee's replacement principle is to enhance the robustness of the program, and maintain excellent compatibility during version upgrades. Even if a subclass is added, the original subclass can continue to run. In the actual project, each subclass corresponds to different business meanings. The parent class is used as the parameter to pass different subclasses to complete different business logic.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.