1, What is object-oriented
The idea of object-oriented (OO) is very important for software development. Its concept and application have even gone beyond program design and software development, and extended to fields such as database system, interactive interface, application structure, application platform, distributed system, network management structure, CAD technology, artificial intelligence and so on. Object oriented is a method of understanding and abstracting the real world. It is the product of the development of computer programming technology to a certain stage.
Procedure oriented is a process centered programming idea. These are programming with the main goal of what is happening, which is different from object-oriented who is affected. The obvious difference from object-oriented is encapsulation, inheritance and class.
Whether in software development or in practical work, it is very necessary to deeply understand the idea of software development.
2, Start with a game
In a software Village
There is a senior "process oriented" programmer - old
And an "Object-Oriented" believer - ah yeah
At the same time, he was employed by a kicked shop
One day, the boss had a whim
Decided to let the two programmers have a competition
The winner will receive a limited amount of money
360 degree automatic massage chair programming
The game began
After a while, they both wrote almost the same code
class Bill{ // Get total price fun getPrice(): Double { val unit = getUnit() val number = getNumber() val price = unit * number return price } // Get unit price fun getUnit(): Double { ... } // Get quantity fun getNumber(): Int { ... } }
The old man smiled when he saw the new demand
He decided to let the new cashier inherit the Bill class
First, add the discount method in the Bill class
And open it
open class Bill{ fun getPrice(): Double { val unit = getUnit() val number = getNumber() val price = unit * number return discount(price) } // Deal with discounts open fun discount(price: Double): Double{ return price } fun getUnit(): Double { ... } fun getNumber(): Int { ... } }
The common charging method is discount
Return price directly in function
The charging method of Tanabata Festival inherits this kind
Implement a 77% discount in the discount function
class LoversDayBill : Bill(){ override fun discount(price: Double): Double { return price * 0.77 } }
When Lao Guo and ah Dui hand over the program to the boss at the same time
Old people have begun to fantasize about their comfortable days in the massage chair in the future
Hearing new needs, I was too old to make complaints about the new group.
Make complaints about the old tune make complaints about getPrice again.
class Bill { fun getPrice(): Double { val unit = getUnit() val number = getNumber() val price = unit * number if (todayIsLoversDay()) { return price * 0.77 } if (todayIsMiddleAutumn() && price > 399) { return price - 200 } if (todayIsNationalDay() && price < 100) { // Generate random numbers from 0 to 9. If it is 0, the order will be exempted. That is: one tenth probability free order val free = Random().nextInt(10) if (free == 0) { return 0.0 } } return price } fun getUnit(): Double { ... } fun getNumber(): Int { ... } fun todayIsLoversDay(): Boolean { ... } fun todayIsMiddleAutumn(): Boolean { ... } fun todayIsNationalDay(): Boolean { ... } }
It looks more and more complicated
Bill class and getPrice method
The old man frowned. He knew that things were far from over
Mid Autumn Festival and National Day
He also needs to be in this complex class
Delete the discount method
God knows the boss will mention it again
What is the demand for unrestrained
Whether adding or deleting code, it is not pleasant to make changes in this too long class. In order to find the location that needs to be modified in a long function, "process oriented" makes Laoguo have to browse a large number of code that has nothing to do with the modification. After careful modification, he has to repeatedly confirm that it will not affect other parts of the class.
Lao Guo prayed silently in the bottom of his heart that this class no longer needs to modify and submit its own program
When a new demand is received
First, the Mid Autumn Festival payment category was added
class MiddleAutumePrice : Bill() { override fun discount(price: Double): Double { if (price > 399) { return price - 200 } return super.discount(price) } }
The national day payment category is added:
class NationalDayBill : Bill() { override fun discount(price: Double): Double { if (price < 100) { // Generate random numbers from 0 to 9. If it is 0, the order will be exempted. That is: one tenth probability free order val free = Random().nextInt(10) if (free == 0) { return 0.0 } } return super.discount(price) } }
One of ah's favorite things about "Object-Oriented" is
I have good news to tell you!
When the boss said this happily
Lao Guo and ah Dui both showed frightened expressions
This sentence often means changing requirements
Lao Guo resisted
But he didn't say another little 99 in his heart
I really don't want to add code to the Bill class
The revision took a long time to complete
class Bill { val gifts = listOf("flower", "chocolate", "9.9 discount") fun getPrice(): Double { val unit = getUnit() val number = getNumber() val price = unit * number if (todayIsLoversDay() && isCouple()) { if (price > 99) { val lucky = Random().nextInt(gifts.size) println("Congratulations on getting ${gifts[lucky]}!") } return price * 0.77 } if (todayIsMiddleAutumn() && price > 399) { return price - 200 } if (todayIsNationalDay() && price < 100) { // Generate random numbers from 0 to 9. If it is 0, the order will be exempted. That is: one tenth probability free order val free = Random().nextInt(10) if (free == 0) { return 0.0 } } return price } fun getUnit(): Double { ... } fun getNumber(): Int { ... } fun todayIsLoversDay(): Boolean { ... } private fun isCouple(): Boolean { ... } fun todayIsMiddleAutumn(): Boolean { ... } fun todayIsNationalDay(): Boolean { ... } }
Look at the gifts variable that only belongs to the Tanabata Festival
Old people feel as bad as looking at oil stains on their white shirts
One will be generated every time you charge in the future
Variables only used on Tanabata
It's all because the boss's needs are too wonderful
To make this program look messy
Because this class has been modified
The code that has passed the test has to be tested again
A pair opened the LoversDayBill class
Amend it as follows
class LoversDayBill : Bill() { val gifts = listOf("flower", "chocolate", "9.9 discount") override fun discount(price: Double): Double { if (!isCouple()) return price if (price > 99) { val lucky = Random().nextInt(gifts.size) println("Congratulations on getting ${gifts[lucky]}!") } return price * 0.77 } fun isCouple(): Boolean { ... } }
When the boss reads the code of Lao Guo and ah Dui
When excited about new needs again
The old man suddenly fainted
The game was so anxious
Who won the prize last?
The third contestant is the stupid son of the boss
He can't write programs at all
But he uses Ctrl+C, Ctrl+V
Copied ah pair's code
3, Common interview sites
In the interview, the common inspection points of object-oriented are three basic characteristics: encapsulation, inheritance and polymorphism.
encapsulation
Encapsulation is to encapsulate objective things into abstract classes, and classes can only allow their own data and methods to be operated by trusted classes or objects, and hide information from untrusted ones.
inherit
Inheritance refers to the ability to use all the functions of an existing class and extend them without rewriting the original class. The new class created by inheritance is called "subclass" or "derived class", and the inherited class is called "base class", "parent class" or "superclass".
Inheritance can be realized through inheritance and composition.
Polymorphism
Polymorphism is a technique that allows you to set a parent object equal to one or more of its children. After assignment, the parent object can operate in different ways according to the characteristics of the child object currently assigned to it. Simply put, it is allowed to assign a pointer of a subclass type to a pointer of a parent type.
There are two ways to realize polymorphism, covering and overloading. The difference between the two is that override is determined at run time and overload is determined at compile time. And the mechanisms of coverage and overloading are different. For example, in Java, the signature of an overloaded method must be different from that of the original method, but it must be the same for the overlay signature.
My understanding of object-oriented: object-oriented programming makes each class do only one thing. Process oriented makes a class more and more versatile and does everything like a housekeeper. Object oriented is like hiring a group of employees. Everyone does a small thing, performs their own duties, and finally cooperates and wins!
4, Extended reading
Finally, what are the benefits of object orientation?
The story that big bird tells Xiaocai in Dahua design mode is very classic:
"During the Three Kingdoms period, Cao Cao led millions of troops to attack Soochow. The troops were stationed in Chibi on the Yangtze River, and the military ships were connected. Seeing that Soochow would be destroyed and the world would be unified, Cao Cao was happy, so he gave a big banquet to all the civil and military forces. During the banquet, Cao Cao was full of poetry and chanted, 'drinking and singing is really cool...' all the civil and military forces shouted together: 'the prime minister is a good poem!' so a minister quickly ordered the seal Brush craftsmen for engraving and printing, so as to spread all over the world. "
"When the sample came out and showed it to Cao Cao, Cao Cao felt that it was inappropriate and said: 'drinking and singing is too vulgar. It should be changed to' singing to wine 'better!' so the minister ordered the craftsman to do it again. The craftsman saw that the engraving work all night was completely wasted, and he kept complaining. He had to do it."
"The sample came out again and asked Cao Cao to have a look. Cao Cao thought it was still bad. He said: 'life is so cool' it's too direct. You should change the language to be artistic conception. Therefore, it should be changed to 'singing to wine, life is geometric...' when the minister told the craftsman, the craftsman fainted..."
Big bird: "little dish, what's the problem?"
Xiao Cai: "is it because movable type printing was not invented during the Three Kingdoms period, so when you want to change the characters, you must re engrave the whole stereotype."
Big bird: "well said! If you have movable type printing, you only need to change four words, and the rest of the work has not been done in vain. Isn't it wonderful.
1, To change, just change the word to be changed, which is maintainable;
2, These words are not useless this time. They can be reused in later printing;
3, If you want to add words to this poem, you just need to add another engraved word, which is extensible;
4, In fact, the arrangement of characters may be vertical or horizontal. At this time, only moving the movable type can meet the arrangement requirements, which is a good flexibility. "
"Before the advent of movable type printing, the above four characteristics could not be met. To modify, you must engrave again, add words, engrave again, rearrange and engrave again. After printing this book, this edition has no reuse value."
Xiao Cai: "yes, when I was a child, I always wondered why gunpowder, compass and papermaking were great inventions from scratch, from unknown to discovery, while movable type printing was only a technological progress from block printing to movable type printing. Why not evaluate printing as one of the four great inventions? It turned out that movable type printing was a success of thought and an object-oriented victory."
----------------------------Here is the original answer-------------------------------
Corresponding to object-oriented, that is, process oriented, which existed in earlier versions of C language.
The process oriented to process development is a bit similar to the tree calling function. The main program of the root node of the tree calls the function layer by layer.
For example, if the main function wants to sort, call sort, and then call the corresponding, and then output after sorting, and then call output. The so-called process oriented process refers to sorting and outputting the corresponding "behaviors" one by one, that is, the process is your operation every time.
Process oriented questions include:
- Poor reusability
According to the process, similar codes in different processes are not easy to reuse. The logic used in the first half of the process needs to be written again if it is used again in the second half. If it is the same logic, there will be many complex problems in modification. - Not easy to expand
For example, if you want to have two copies of similar logic for the same logic, you often need to write two copies in the process oriented. - High coupling
There is a very appropriate metaphor, saying that process oriented is fried rice with eggs, and object-oriented is fried rice with cover, that is, process oriented is difficult to peel off the content and mix them together. If you want to change one thing, you often change the full text; When object-oriented is changed, it is changed less. But process oriented is also beneficial. Iterative rapid development. In some cases, such as writing a program in a 48 hour competition, rapid iteration and process segmentation are more suitable for process oriented development.
The difference between object-oriented and process oriented is:
Object oriented is based on elements and things as the main body. As long as you can abstract something into an object, it can be used as the carrier of your piece of code.
For example, MVC abstracts the data, page and control of one thing into one thing and couples them separately. Different objects only provide corresponding interfaces, and the connection is also based on the corresponding interfaces. Encapsulating each object into a class is what object-oriented needs to do.
First of all, the reusability is excellent. If you want to write repetitive logic, just use the same class directly.
Secondly, the coupling is very low. When modifying the logic, you only need to modify the content in the corresponding interface.
At the same time, the code logic is better understood and maintained.