Six principles of design patterns (2)

Source: Internet
Author: User
ArticleDirectory
    • What is Lee's replacement principle?
    • Summary

Today is 3.15, a special day. I don't know how many bad companies will be exposed, and I don't know if the number of hidden companies that have not been exposed exceeds my imagination. Every year, new keywords such as "plasticizer, toxic capsules, problematic milk, and fast-growing chicken" are reported. They enter the restaurant, enter the canteen, and enter the supermarket. They really don't know what to touch. New problems are exposed year by year, but year by year. Is there a bottom line for poor businesses? What about good exercises?

Design Pattern Series
    • Six principles of design model (1): single Responsibility Principle
    • Six principles of design patterns (2)
    • Six principles of design patterns (3): Dependency inversion principle
    • Six principles of design mode (4): interface isolation principle
Origin

We all know that Object-oriented has three main features: encapsulation, inheritance, and polymorphism. Therefore, in the actual development process, after the child class inherits the parent class, according to the characteristics of polymorphism, it may be convenient for the graph at the moment, and the method of the parent class is often rewritten arbitrarily. This method will greatly increaseCodeThe probability of a problem. For example, in the following scenario: Class C implements a function F1. Now you need to modify and extend the feature F1 to F, where F is composed of the original feature F1 and new feature F2. The new function f is completed by the subclass C1 of class C. When the subclass C1 completes the function f, it may cause the F1 of the original function of class C to fail. At this time, the Lee replacement principle was unveiled.

What is Lee's replacement principle?

The single responsibility principle mentioned above is easy to understand from the literal meaning, but the replacement principle is a bit confusing. After checking the information, I found that this principle was first established in 1988 by a lady surnamed Li (Liskov.

Abbreviation: LSP (liskov substitution principle ).

strict definition: if each type is t1 > Object O1, all types are T2 Object O2 , t1 all Program P all objects O1 replace all with O2 , program P change, type t2 Yes t1 child type.

Common Definition: all objects that reference the base class must be transparently used.

More common definition: Child classes can expand the features of the parent class, but cannot change the original features of the parent class.

Sample Code

 
// Abstract parent computer public abstract class computer {public abstract void use ();} class IBM extends computer {@ overridepublic void use () {system. out. println ("use IBM computer. ") ;}} class HP extends computer {@ overridepublic void use () {system. out. println ("use HP computer. ") ;}} public class client {public static void main (string [] ARGs) {computer IBM = new IBM (); computer HP = new HP (); // objects of the Child classes can be transparently used where the base classes are referenced. IBM. Use (); HP. Use ();}}
Layer-4 meaning

The Lee's replacement principle includes the following four meanings:

    • Sub-classes can implement abstract methods of parent classes, but cannot overwrite non-Abstract methods of parent classes.
    • Sub-classes can add their own unique methods.
    • When subclassOverwrite or implementWhen a method of the parent class is used, the preconditions of the method (that is, the parameters of the method) are looser than the input parameters of the parent class method.
    • When the subclass method implements the abstract method of the parent class, the post-condition (that is, the return value of the method) of the method is stricter than that of the parent class.

Now we can explain the meanings of the above four layers one by one.

Sub-classes can implement abstract methods of parent classes, but cannot overwrite non-Abstract methods of parent classes.

When designing a system, we often design interfaces or abstract classes, and then use subclasses to implement abstract methods. Here, we actually use the Rys replacement principle. Sub-classes can implement the abstract methods of the parent class. In fact, sub-classes must fully implement the abstract methods of the parent class. If you write an empty method, an error will be reported during compilation.

The key point of the Lee's replacement principle is that it cannot overwrite non-abstract methods of the parent class. In the parent class, all methods that have been implemented are actually setting a series of specifications and contracts, although it does not force all subclasses to comply with these specifications, however, if the subclass modifies these non-Abstract METHODS randomly, the entire inheritance system will be damaged. The principle of Lishi replacement is to express this layer of meaning.

In the object-oriented design philosophy, the inheritance feature brings great convenience to the system design, but it also has some potential risks. Just like the scenario mentioned in the beginning, it is best to follow the Lee's replacement principle in that case. When Class C1 inherits Class C, you can add new methods to complete new functions, try not to override the method of parent class C. Otherwise, unexpected risks may occur. For example, the following simple example is used to restore the scenario:

Public class c {public int func (int A, int B) {return a + B;} public class C1 extends c {@ overridepublic int func (int A, int B) {return a-B ;}} public class client {public static void main (string [] ARGs) {c = new C1 (); system. out. println ("2 + 1 =" + C. func (2, 1 ));}}

Running result: 2 + 1 = 1

The above running results are obviously incorrect. Class C1 inherits Class C, and then new functions need to be added. Class C1 does not write a new method, but directly overwrites the func method of the parent class C, which violates the Rys replacement principle, when the parent class is referenced, The subclass object cannot be used transparently, resulting in an error in the running result.

You can add methods that are unique to sub-classes.

While inheriting the attributes and methods of the parent class, each subclass can have its own personality and expand its functions on the basis of the parent class. As mentioned above, when the function is extended, the subclass should try not to rewrite the method of the parent class, but write another method. Therefore, the code above should be modified to conform to the lee's replacement principle, the Code is as follows:

 
Public class c {public int func (int A, int B) {return a + B;} public class C1 extends c {public int func2 (int A, int B) {return a-B ;}} public class client {public static void main (string [] ARGs) {C1 c = new C1 (); system. out. println ("2-1 =" + C. func2 (2, 1 ));}}

Running result: 2-1 = 1

When subclassOverwrite or implementWhen a method of the parent class is used, the preconditions of the method (that is, the parameters of the method) are looser than the input parameters of the parent class method.

Sample Code

 
Import Java. util. hashmap; public class father {public void func (hashmap m) {system. out. println ("execution parent class... ") ;}} import Java. util. map; public class son extends father {public void func (MAP m) {// the parameter of the method is looser than that of the parent class. out. println ("execution subclass... ") ;}} import Java. util. hashmap; public class client {public static void main (string [] ARGs) {father f = new son (); // objects of the Child classes can be transparently used where the base classes are referenced. Hashmap H = new hashmap (); F. func (h );}}

Running result: Execute the parent class...

Note that @ override annotation cannot be added before the son class func method, because otherwise, an error will be reported during compilation, because this is not override, but overload ), because the input parameters of the method are different. The difference between rewriting and overloading is thatJava object-oriented explanationThis article has been explained and will not be detailed here.

When the subclass method implements the abstract method of the parent class, the post-condition (that is, the return value of the method) of the method is stricter than that of the parent class.

Sample Code:

Import Java. util. map; public abstract class father {public abstract map func ();} import Java. util. hashmap; public class son extends father {@ overridepublic hashmap func () {// the return value of the method is stricter than that of the parent class. hashmap H = new hashmap (); H. put ("H", "execution subclass... "); Return H ;}} public class client {public static void main (string [] ARGs) {father f = new son (); // objects of the Child classes can be transparently used where the base classes are referenced. System. Out. println (F. func ());}}

Execution result: {H = Execution subclass ...}

Summary

Inheritance, as one of the three main characteristics of object-oriented programming, brings great convenience while also brings some drawbacks. It increases the coupling between objects. Therefore, in the system design, we should follow the Rits replacement principle and try to avoid subclass rewriting of the parent class, which can effectively reduce the possibility of code errors.

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.