The principle of design pattern principle of the Richter substitution

Source: Internet
Author: User

On the Richter scale substitution principle, the OCP, as the high-level principle of OO, advocates the use of "abstract (abstraction)" and "polymorphic (polymorphism)" To change the static structure of the design to the dynamic structure and maintain the sealing of the design. "Abstraction" is a feature provided by the language. Polymorphism is implemented by inheritance semantics.

Definition 1: If for each object of type T1, there is an object O2 of type T2, so that all program P defined by T1 is replaced with O1 for all objects O2, the behavior of program p does not change, then type T2 is a subtype of type T1.

definition 2: All references to base classes must be able to transparently use objects of their subclasses.

If you think the definition of vague point, not very clear, it's OK, we slowly speak clearly. Another short definition of the Richter substitution principle is that "all references to base classes must be able to use objects of their subclasses transparently". This may be a little clearer. If you are familiar with an object-oriented language, you should be able to understand object-oriented inheritance, the subclass inherits from the parent class, and naturally inherits all the methods of the parent class (assuming the parent class does not declare the method private).

Inheritance has many advantages in object-oriented:

1 code sharing, reducing the effort to create classes, each of which has methods and properties of the parent class;

2 Improve the reusability of code;

3 subclasses can resemble the parent class, but also different from the parent class, "Dragon Born Dragon, chicken born chicken, the mouse is born to play the hole" is said the son has the father's "kind", "the world No two identical leaves" is the point child and the Father difference;

4 Improve the extensibility of the Code, the implementation of the parent class method can "do what you Want", you do not see a lot of open source framework of the extension interface is through the inheritance of the parent class to complete;

5 improve the openness of products or projects.

And the Richter replacement principle is that you should try not to change the original method while writing a class that inherits from the original class. If there is so much to say, then there must be doubt.

problem Origin: There is a functional P1, which is done by Class A. Now need to extend the function P1, the function of the extension is P, where p is composed of the original function P1 and the new function P2. The new function p is done by subclass B of Class A, and sub-class B, while completing the new function P2, may cause the original function P1 to fail.

Solution: Follow the Richter substitution principle when using inheritance. When Class B inherits from Class A, try not to rewrite the parent class A's method, but also try not to reload the parent Class A's method, except to add a new method to complete new functionality P2.

Inheritance contains a layer of meaning: in a parent class, a well-implemented method (as opposed to an abstract method) is actually a set of specifications and contracts, although it does not enforce that all subclasses must comply with these contracts, but if the subclasses arbitrarily modify these non-abstract methods, the entire inheritance system will be destroyed. The principle of replacing the Richter scale is to express this level of meaning.

As one of the three characteristics of object-oriented, inheritance brings great convenience to program design, and it also has drawbacks. For example, the use of inheritance will be intrusive to the program, the portability of the program, increase the coupling between objects, if a class is inherited by other classes, when the class needs to be modified, must take into account all subclasses, and after the parent class modification, all the functions that involve subclasses are likely to fail.

To illustrate the risk of inheritance, we need to complete a two-digit subtraction function, which is the responsibility of Class A.

classa{ Public intFunc1 (intAintb) {        returnA-b; }} Public classclient{ Public Static voidMain (string[] args) {A a=NewA (); System.out.println ("100-50=" +A.FUNC1 (100, 50)); System.out.println ("100-80=" +a.func1 (100, 80)); }}

Operation Result:

100-50=50100-80=20

Later, we need to add a new function: Complete the two-number addition, and then sum it up with 100, which is the responsibility of Class B. That is, Class B needs to complete two functions:

    • Subtract two numbers.
    • The two numbers are added and then added 100.

Since Class A has already implemented the first function, Class B inherits Class A and only needs to complete the second function, the code is as follows:

classBextendsa{ Public intFunc1 (intAintb) {        returnA +b; }         Public intFunc2 (intAintb) {        returnFunc1 (A, b) +100; }} Public classclient{ Public Static voidMain (string[] args) {b b=NewB (); System.out.println ("100-50=" +B.FUNC1 (100, 50)); System.out.println ("100-80=" +b.func1 (100, 80)); System.out.println ("100+20+100=" +B.FUNC2 (100, 20)); }}

After Class B is complete, run the result:

100-50=150100-80=180100+20+100=220

We found that the normal subtraction function had been wrong. The reason is that Class B inadvertently overrides the method of the parent class when giving the method a name, causing all code that runs the subtraction function to call the overridden method of Class B, resulting in an error in the function that was normally functioning. In this example, an exception occurs after a function that references the completion of base class A is replaced with subclass B. In the actual programming, we often by rewriting the parent class method to complete the new function, so that although simple to write, but the entire inheritance system reusability will be poor, especially when the use of polymorphic more frequent, the probability of the program run error is very large. If you do not want to override the method of the parent class, the common practice is that the original parent class and subclass inherit a more popular base class, the original inheritance relationship is removed, the dependency, aggregation, composition and other relationships are substituted.

The principle of the Richter substitution is popular: subclasses can extend the functionality of the parent class, but cannot change the original functionality of the parent class. it contains the following 4 levels of meaning:

    • Subclasses can implement the abstract methods of the parent class, but cannot override the non-abstract methods of the parent class.
    • Subclasses can add their own unique methods.
    • When a method of a subclass overloads a method of the parent class, the method's preconditions (that is, the parameter of the method) are more lenient than the input parameters of the parent class method.
    • When a method of a subclass implements an abstract method of the parent class, the post condition of the method (that is, the return value of the method) is stricter than the parent class.

It looks incredible, because we will find that in our own programming often violates the Richter scale replacement principle, the program still runs well. So everyone will have this question, if I do not follow the Richter scale replacement principle will have what consequences?

The consequence is that the odds of your code writing will increase dramatically.

Reproduced in http://blog.csdn.net/zhengzhb/article/details/7281833

The Richter substitution principle of the design pattern principle

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.