Six principles of the design model (2)-the principle of the replacement of Lishi and the six major design models

Source: Internet
Author: User
Tags define abstract

Six principles of the design model (2)-the principle of the replacement of Lishi and the six major design models

Definition:

Objects in a program should be replaced by its subclass without changing the program's correctness. That is to say, all objects that reference the base class must be transparently used. In general, child classes can extend the functions of the parent class, but cannot change the original functions of the parent class.

Origin:

The first time I saw the name of this Lee's replacement principle, I felt very strange. According to my previous experience, this was the first concept proposed by a foreign friend. Then I named it by her surname. Indeed, it was first proposed by Barbara Liskov in a speech titled "data abstraction and hierarchy" at a conference in 1987. The default English name is Liskov Substitution principle. Therefore, LSP is short for this principle.

In-depth:

The Lee replacement principle defines a standard for good inheritance. A simple definition contains four meanings:

  • Subclass must fully implement the parent class Method

When designing a system, we often write interfaces and abstract classes, and then encode them to inherit them. In fact, here we have applied the Lee's replacement principle. For example, we can simply implement various guns in CS (define abstract classes and then inherit from them). The gun class diagram is as follows:

/// <Summary> // gun abstract class // </summary> public abstract class implements actgun {public abstract void Shoot ();} /// <summary> /// shou gun /// </summary> public class HandGun: AbstractGun {public override void Shoot () {Console. writeLine ("shou gun shot... ") ;}//< summary> /// Rifle /// </summary> public class Rifle: AbstractGun {public override void Shoot () {Console. writeLine ("rifle shot... ") ;}/// <summary> /// machine gun // </summary> public class MachineGun: AbstractGun {public override void Shoot () {Console. writeLine ("Machine gun shooting... ") ;}/// <summary> // soldier class /// </summary> public class Solder {public void KillEnemy (AbstractGun gun) {Console. writeLine ("soldiers start killing... "); gun. shoot ();}}

The scenario class (main function) code is as follows:

class Client    {        static void Main(string[] args)        {            var solder = new Solder();            solder.KillEnemy(new Rifle());            Console.ReadKey();        }     }

The running result is as follows:

Note that it is necessary to use the parent class or interface when calling other classes in the class. If the parent class or interface cannot be used, it indicates that the class design has violated the LSP principle.

If we want to marry a toy gun now, we will add a TonyGun class to inherit AbstractGun. After adding the toy gun, the new class is shown as follows:

/// <Summary> /// toy gun /// </summary> public class TonyGun: AbstractGun {public override void Shoot () {// the toy gun cannot be shot, this cannot be implemented here }}

The Demo code is as follows:

class Client    {        static void Main(string[] args)        {            var solder = new Solder();            solder.KillEnemy(new TonyGun());            Console.ReadKey();        }     }

The running result is as follows:

Associated Delegation
 

Note: If the subclass cannot fully implement the parent class method, or some methods of the parent class have been "distorted" in the subclass, we recommend that you disconnect the Parent-Child inheritance relationship, inheritance is replaced by dependency, aggregation, and combination.

 

  • Subclass can have its own personality

Sub-classes can certainly have their own behaviors and appearances (that is, methods and attributes). Why do we mention them here? Because the Rys replacement principle cannot be used here, child classes can replace parent classes, but parent classes cannot replace parent classes (if they can be replaced, there is no need to derive child classes ), I will not explain the specifics (the definition is so simple, and the principle is quite simple). I will give a brief description using the following figure:

The preconditions of the method in the subclass must be the same or looser than that of the method that is overwritten in the superclass..

  • Output results can be reduced when override or parent classes are implemented.

What does this mean? The Return Value of a method of the parent class is a type T, and the return value of the same method (overload or overwrite) of the subclass is S, in this case, the 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. Why? In two cases, if it is overwriting, the input parameters of the methods with the same name as the parent class and subclass are the same, and the range value S of the two methods is less than or equal to T, which is the overwriting requirement, this is the top priority. sub-classes override the parent class method. If it is a heavy load, the input parameter type or quantity of the method must be different. In the requirements of the Rys replacement principle, the input parameter of the subclass is greater than or equal to the input parameter of the parent class, that is to say, the method you write will not be called. Refer to the prerequisites mentioned above.
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 actual projects, each subclass corresponds to different business meanings. It is perfect to use the parent class as a parameter to pass different subclasses to complete different business logic!

Summary:

It looks incredible, because we will find that in our own programming, we often violate the Lee's replacement principle, and the program runs well. So everyone will have such questions. What would happen if I did not follow the Lee's replacement principle?
The consequence is that the chances of problems with the code you write will be greatly increased.

PS: at the end of the submission, I was prompted that the [hand-gun] was a prohibited word, so I had to change it to the shou gun.


C #'s replacement principle

In the object-oriented thinking, it can be seen that a derived class has all the features that the base class exposes downward. It is a special case of the base class.
When a derived class object is assigned to a base class type, the data structure of the derived class corresponds to the data structure of the Base class in sequence. The data of the derived class is invisible.

When the base class object attempts to convert to a derived type, the data of the base class object cannot be filled with all the data structures of the derived class in sequence. This makes it impossible to complete the function defined by the derived class. The compiler will prompt or even report an error.
This is why the derived class is competent for the basic class function, but the base class is not fully competent for the function of the derived class.
Forced conversion belongs to the process from the base class to the derivation: the designer knows that the data structure of the Base Class Object can completely fill the structure of the derived class. Otherwise, a forced conversion error occurs. It is generally best to avoid strong conversion!

Also, it is not entirely correct that subclass can appear in any parent class object, and sometimes some members of the parent class will not be exposed to the subclass.
References: None

In java, what is the replacement principle of Lishi?

The subclass can replace the parent class.

That is, where the parent class appears, it can be replaced by a subclass.

Switch does not exist.

Related Article

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.