Golang OOP, inheritance, combination, interfaces

Golang OOP, inheritance, combination, interfaces

traditional oop concept

OOP (Object Oriented Programming) is an abstract way of thinking of the real world, can better manage the relationship between the entity and the entities involved in the higher level.

Wide spread of the three elements of OOP are: encapsulation, inheritance, polymorphism.

Object: it can be seen as a collection of some of the features, which is mainly characterized by the properties and methods embodied.
Package: delineation of the boundaries of the object, which is the definition of the object.
Inheritance: shows the relationship between the parent and child objects, the child object is an extension of the parent object, in fact, the child object "is" parent. Equivalent to saying that "agriculture is the man code." From the collection of the sense feature that contains the parent object child object parent object some common features, all have sub-objects.
Polymorphism: The meaning of inheritance, child objects on the all-around characteristics of the parent object, therefore, when needed parent object, the child object can replace the parent.

java-oop: extends and implements

extends can be understood as the overall functionality of the parent class inherits

Class Human {
    name:string
    age:int
    function eat(){}
    function speak(){}
}

Class Man extends Human {
    function fish(){}
    function drink(){}
}

implements can be understood as attach some additional functionality to this class
for example, Animal is a parent, cat, dog, bird, insect both extends the Animal,
but the cat, dog, bird also implements such as run, shout these interface, bird, insect can fly implements such as these interface

interface keyword defines an interface is the so-called interface that white is a rule, an analogy with a computer's USB jack

public interface USB接口{
这个接口只能插标准USB接口();/*所谓接口中的方法就是定义了个规范,而我这个标准USB接口中要插鼠标还是优盘,那就是在你的实现类中根据具体情况来看了*/
}

The key is to implement implementation of the interface, if you reality of an interface, it must implement the methods inside, the example above goes on to say

public class 类名 implement USB接口{
//现在就要具体实现刚才接口中定义的方法了,
接口中的方法(){
我这个接口是插鼠标的;
}

That is, the original basis of your class on and the introduction of other methods, like computer, a touch panel, but the introduction of USB ports I can plug the mouse, you can plug speakers, is a functional expansion
extendes, it inherited keyword, is subclass inherits the parent class functions and properties
, but also use a computer analogy, is a computer class, there are a monitor, keyboard these properties, the laptop is a class that has all the attributes of a computer, but the addition of other attributes than the computer and function, the laptop is derived from the computer there, so we called the father of the computer class is a subclass of the notebook, empathy desktop computer is a subclass of a class can have multiple sub-class, but a class can only there is a direct parent
difference extendes interface and the
interface implements the interface all methods in the interface must be implemented
extendes inherited the properties and methods of the parent class, but may never be irrelevant

Golang of OOP, golong using a combination rather than inheritance

As can be seen from the code below, is not the same as java, the order parameter as a function of human Student used directly, or can not h = s
However, human methods can be used, such as s func (h Human) {fmt.Println (h.name)}
this behavior is different from the language of Java classes, but also from prototype chain to inherit behavior, golang called the Embedding, which like a parasitic relationship: Human parasites in the Student but still maintain a certain degree of independent.

package main

import "fmt"

func main(){
    var h Human
    s := Student{Grade: 1, Major: "English", Human: Human{Name: "Jason", Age: 12, Being: Being{IsLive: true}}}
    fmt.Println("student:", s)
    fmt.Println("student:", s.Name, ", isLive:", s.IsLive, ", age:", s.Age, ", grade:", s.Grade, ", major:", s.Major)
    //h = s // cannot use s (type Student) as type Human in assignment
    fmt.Println(h)
    //Heal(s) // cannot use s (type Student) as type Being in argument to Heal
    // HealHuman(s) // # command-line-arguments
    //./10_1_oop.go:13:14: cannot use s (type Student) as type Human in argument to HealHuman
    HealHuman(s.Human)
    Heal(s.Human.Being) // true
    s.Drink()
    s.Eat()
}

type Car struct {
    Color string
    SeatCount int
}

type Being struct {
    IsLive bool
}

type Human struct {
    Being
    Name string
    Age int
}

func (h Human) Eat(){
    fmt.Println("human eating...")
    h.Drink()
}
 
func (h Human) Drink(){
    fmt.Println("human drinking...")
}
 
func (h Human) Move(){
    fmt.Println("human moving...")
}
 
type Student struct {
    Human
    Grade int
    Major string
}
 
func (s Student) Drink(){
    fmt.Println("student drinking...")
}
 
type Teacher struct {
    Human
    School string
    Major string
    Grade int
    Salary int
}
 
func (s Teacher) Drink(){
    fmt.Println("teacher drinking...")
}

type IEat interface {
    Eat()
}
 
type IMove interface {
    Move()
}
 
type IDrink interface {
    Drink()
}
 
 
func Heal(b Being){
    fmt.Println(b.IsLive)
}

func HealHuman(h Human){
    fmt.Println(h.Being)
}


// output
student: {{{true} Jason 12} 1 English}
student: Jason , isLive: true , age: 12 , grade: 1 , major: English
{{false}  0}
{true}
true
student drinking...
human eating...
human drinking...

Golang interface

Let us consider the reasons for the interface generated.
Code for processing a variety of data. For strongly typed language, very much like a batch of data is a single type, so that they behave exactly the same. But the world is complex, very often the data might contain different types, there are one or more common. The common denominator is abstract foundation. Single inheritance is-a relationship to solve the problem is defined, it can handle the class as a parent class to be treated. But different for parent but have some common behavior data, single inheritance can not be solved. Single inheritance structure is a tree structure, but the real world is more common network structure.
So with the interface. Interface is an abstract in one respect, the label can also be seen as having some of the same things that behavior.
But unlike succession, the interface is a loose structure, and it does not define the binding. From that point on, Duck Type compared to traditional extends is more loosely coupled way, while the data abstracted from multiple dimensions to find out they have in common, used to process the same set of logic.

The Java interface mode is mandatory mode implemented after the first statement, for example, you want to tell everyone you speak English, and will be speaking and writing, you only have the English skills.

interface IEnglishSpeaker {
     ListenEnglish()
     ReadEnglish()
     SpeakEnglish()
     WriteEnglish()
}

Different Golang, you will not need to declare your English speaking and writing as long as you can, and you will be English. That is achieved determines the concept: If a person in the school (there School, Grade, Class of these properties), but also to learn (there Study () method), then that person is a student.
Duck Type more in line with human cognitive processes of the real world: We always know by different individuals to summarize and abstract concepts and definitions. That's basically the preliminary work in software development, modeling abstraction.
In comparison, Java approach is to define the relationship (interfaces), and then to realize, this is more like from the perspective of God's plan to produce defined concepts, then creation.

Because the loose coupling between the interface and the object, Golang such a manner as to determine a type assertion is not a type interfaces:
value, B: = interface (Type). , The default value Example Type; b. A bool type, It shows that the assertion holds.

interface judgment

// 接上面的例子

v1, b := interface{}(s).(Car)
fmt.Println(v1, b)

v2, b := interface{}(s).(Being)
fmt.Println(v2, b)

v3, b := interface{}(s).(Human)
fmt.Println(v3, b)

v4, b := interface{}(s).(Student)
fmt.Println(v4, b)

v5, b := interface{}(s).(IDrink)
fmt.Println(v5, b)

v6, b := interface{}(s).(IEat)
fmt.Println(v6, b)

v7, b := interface{}(s).(IMove)
fmt.Println(v7, b)

v8, b := interface{}(s).(int)
fmt.Println(v8, b)

The above code, using empty interface to interface {} s were cast as a struct s, not the interface, the type and number of the left side in claim assertion expression must interface.

{ 0} false
{false} false
{{false}  0} false
{{{true} Jason 12}  1 English} true
{{{true} Jason 12}  1 English} true
{{{true} Jason 12}  1 English} true
<nil> false
false

Common usage-based interface similar paradigm

s1 := Student{Grade: 1, Major: "English", Human: Human{Name: "Jason", Age: 12, Being: Being{IsLive: true}}}
s2 := Student{Grade: 1, Major: "English", Human: Human{Name: "Tom", Age: 13, Being: Being{IsLive: true}}}
s3 := Student{Grade: 1, Major: "English", Human: Human{Name: "Mike", Age: 14, Being: Being{IsLive: true}}}
t1 := Teacher{Grade: 1, Major: "English", Salary: 2000, Human: Human{Name: "Michael", Age: 34, Being: Being{IsLive: true}}}
t2 := Teacher{Grade: 1, Major: "English", Salary: 3000, Human: Human{Name: "Tony", Age: 31, Being: Being{IsLive: true}}}
t3 := Teacher{Grade: 1, Major: "English", Salary: 4000, Human: Human{Name: "Ivy", Age: 40, Being: Being{IsLive: true}}}
drinkers := []IDrink{s1, s2, s3, t1, t2, t3}

for _, v := range drinkers {
    switch t := v.(type) {
    case Student:
        fmt.Println(t.Name, "is a Student, he/she needs more homework.")
    case Teacher:
        fmt.Println(t.Name, "is a Teacher, he/she needs more jobs.")
    default:
        fmt.Println("Invalid Human being:", t)
    }
}

output:

Jason is a Student, he/she needs more homework.
Tom is a Student, he/she needs more homework.
Mike is a Student, he/she needs more homework.
Michael is a Teacher, he/she needs more jobs.
Tony is a Teacher, he/she needs more jobs.
Ivy is a Teacher, he/she needs more jobs.

why no longer oop in go ?

James Gosling :
I once attended a Java user group meeting where James Gosling (Java’s inventor) was the featured speaker.
During the memorable Q&A session, someone asked him: “If you could do Java over again, what would you change?”
“I’d leave out classes,” he replied. After the laughter died down, he explained that the real problem wasn’t classes per se, but rather implementation inheritance (the extends relationship). Interface inheritance (the implements relationship) is preferable. You should avoid implementation inheritance whenever possible.

reference: https://www.cnblogs.com/jasonxuli/p/6836399.html

Guess you like

Origin www.cnblogs.com/wangjiale1024/p/11237167.html