Golang object-oriented programming

Golang object-oriented programming

*Catalog
00 Golang language object-oriented programming instructions
01 Fields, attributes
02 Method
03 Object-oriented programming
04 Factory mode
05 Object-oriented programming ideas*

00 Golang language object-oriented programming instructions

  • Golang also supports object-oriented programming (OOP), but it is different from traditional object-oriented programming and is not a pure object-oriented language. Therefore, it is more accurate to say that Golang supports object-oriented programming features.

  • Golang has no class. The structure of Go language has the same status as the class of other programming languages. You can understand that Golang implements OOP features based on struct.

  • Golang object-oriented programming is very concise, removing the inheritance of traditional OOP language, method overloading, constructor and destructor, hidden this pointer, etc.

  • Golang still has the inheritance, encapsulation and polymorphism characteristics of object-oriented programming, but the implementation is different from other OOP languages, such as inheritance: Golang does not have the extends keyword, and inheritance is achieved through anonymous fields.

  • Golang object-oriented (OOP) is very elegant, OOP itself is a part of the language type system (type system), through the interface (interface) association, low coupling, and very flexible. In other words, interface-oriented programming is a very important feature in Golang.

The difference and connection between structure and structure variable (instance)

  • Structure is a custom data type, representing a class of things

  • Structure variables (instances) are concrete, actual, and represent a concrete variable

How to declare a structure

type structure name struct { 
    field1 type 
    field2 type 
    ... 
}

Define Dog structure

type Dog struct{
    Name string
    Age int64
    Color string}

01 field, attribute

  • From the concept or name point of view: structure field = attribute = field

  • The field is a component of the structure, generally a basic data type, an array, but also a reference type

Notes and details

  • The syntax of field declaration is the same as that of variables, example: field name field type

  • The type of the field can be: basic type, array or reference type

  • After creating a structure variable, if no value is assigned to the field, it corresponds to a zero value (the default value), and the rules are the same as the previous ones:

    • Use slice to make sure: p1.slice1=make([]int,10)

    • Use map to make sure: p1.map1=make(map[string]string)

    • The boolean type is false, the value is 0, and the string is ""

    • The default value of the array type is related to its element type, for example, score [3] int is [0,0, 0]

    • The zero value of pointer, slice, and map are all nil, that is, no space has been allocated yet

  • The fields of different structure variables are independent and do not affect each other, and the structure is a value type.

Create structure variables and access structure fields

var dd Dogvar dd Dog = Person{"小花",4,"red"}var dd *Dog = new(Dog)
(*dd).Name = "小花"    dd.Name = "小花"        var dd *Dog = &Dog{"小花",4,"red"}var dd *Dog = &Dog{}
(*dd).Name = "小花"    dd.Name = "小花"

Description:

1) 
The third and fourth methods return structure pointers. 2) 
The standard way for structure pointers to access fields should be: (*Structure pointer). Field name, 
such as (*person).Name = "tom" 3) But go has made a simplification and 
also supports structure pointers. Field 
First name, such as person.Name = "tom". 3) The 
bottom layer of the go compiler has converted person.Name (*person).Name.

Precautions and details for structure use

  • All fields of the structure are continuous in memory

  • The structure is a type defined separately by the user, and it needs to have exactly the same fields (name, number and type) when converting with other types

  • The structure is redefined by type (equivalent to aliasing). Golang considers it to be a new data type, but it can be forced to transfer to each other

  • A tag can be written on each field of the struct, and the tag can be obtained through the reflection mechanism. The common usage scenarios are serialization and deserialization.

02 method

The method in Golang works on the specified data type (ie: bound to the specified data type), so custom types can have methods, not just struct.

Method declaration and call

type A struct {
    Num int}func (a A) test(){
    fmt.Println(a.Num)
}

Description

  • func(a A) test (The book indicates that the A structure has a method, the method is called test

  • (aA) reflects that the test method is bound to type A

package mainimport( "fmt")type Person struct { 
    Name string}func (P Person) test({ 
    fmt.Println("test((name=",p.Name)func main(){ var p Personp.Name = " tom" 
    p.test()//Call method 
} 

//1) The test method is bound to the Person type 
//2) The test method can only be called by a variable of the Person type, and cannot be called directly, nor can other types of variables be used To call 
// func (p Person) test()....p represents which Person variable is called, and this p is a copy of it, which is often similar to function passing. 
//4) The name p is specified by the programmer and is not fixed. For example, it can be changed to person

The principle of method call and parameter transfer mechanism

  • When calling a method through a variable, the calling mechanism is the same as that of a function

  • The difference is that when the variable calls the method, the variable itself will also be passed to the method as a parameter (if the variable is a value type, then the value is copied, if the variable is a reference type, then the address is copied)

Notes and details of the method

  • The structure type is a value type. In the method call, the transfer mechanism of the value type is observed, which is the value copy transfer method

  • If the programmer wants to modify the value of the structure variable in the method, it can be handled by the structure pointer

  • The methods in Golang act on the specified data type (ie: bind to the specified data type), so custom types can have methods, not just struct, such as int, float32, etc. can have methods

  • The rules for controlling access scope of methods are the same as those for functions. The first letter of the method name is lowercase and can only be accessed in this package. The first letter of the method is capitalized and can be accessed in this package and other packages.

  • If a type implements the String() method, then fimt.PrintIn will call String() of this variable for output by default

Value copy and address copy in type binding

  • Regardless of the call form, the real decision is value copy or address copy, depending on which type the method is bound to.

  • If it is a sum value type, such as (p Person), it is a value copy, and if it is a pointer type, such as (p*Person), it is an address copy.

  • Address copy can modify the attributes in the binding type

03 Object-oriented programming

step

  • Declare (define) the structure, determine the name of the structure

  • Write the fields of the structure

  • Method of writing structure

Specify field values ​​when creating structure variables

var stu1 =Stu{"小明",19} var stu3 = Stu{ 
    Name: "jack", 
    Age: 20, 
}var stu5 *stu = &stu{"小王",29}var stu7 =&stu{ 
    Name :"小Lee", 
    Age :49, 
}

04 Factory Mode

Golang's structure has no constructor, and the factory pattern can usually be used to solve this problem.

The first letter S of the Student of the structure is capitalized. If we want to create an instance of the Student in other packages (such as the main package) and import the model package, we can directly create the variables (instances) of the Student structure. But here comes the problem. If the first letter is lowercase, such as type student struct, it won't work. How to do? Factory model to solve.

Use the factory pattern to create structure instances (variables) across packages

type student struct{
Name stringscore float64)


fune Newstudent(n string, s float64) *student {return &student{
    Name : n,
    Score : s,
}

05 Object-oriented programming ideas

abstract

When we define a structure before, we actually extract the common attributes (fields) and behaviors (methods) of a class of things to form a physical model (structure). This method of studying a problem is called abstraction.

Encapsulation

Golang still has the inheritance, encapsulation and polymorphism features of object-oriented programming, but the way it is implemented is different from other OOP languages.

Encapsulation is to encapsulate the abstracted fields and the operations on the fields. The data is protected internally, and other packages of the program can only operate on the fields through authorized operations (methods).

Understanding and benefits of encapsulation

  • Hide implementation details

  • The data can be verified to ensure safety and reasonableness (Age)

How to reflect encapsulation

  • Encapsulate the attributes in the structure

  • Through the method, the package realizes the encapsulation

Encapsulation realization steps

  • Lowercase the first letter of structure and field (attribute) (cannot be exported, other packages cannot be used, similar to private)

  • Provide a factory mode function for the package where the structure is located, with the first letter capitalized. Similar to a constructor

  • Provide a Set method with initial capital letters (similar to public in other languages) for judging and assigning attributes

  • Provide a Get method with initial capital letters (similar to public in other languages) to get attributes

Special Note:

In Golang development, there is no special emphasis on encapsulation. This is not like Java. Golang itself simplifies the object-oriented features.

type person struct {
    Name string
    age int        }func NewPerson(name string) *person {    return &person{
        Name : name,
    }
}func (p*person) setAge(age int) {    if age >0 && age <150 {
        p.age = age
    }else{
        fmt.Print1n("年龄范围不正确..")
    }
}func (p*person) GetAge() int {    return p.age
}

inherit

Inheritance can solve code reuse and make our programming closer to human thinking.

When multiple structures have the same properties (fields) and methods, the structure can be abstracted from these structures, and these same properties and methods can be defined in the structure.

The basic syntax of nested anonymous structures

type Goods struct {
    Name stringPrice int}type Book struct {
    Goods        
    Writer string}

In-depth discussion of inheritance

  • The structure can use all the fields and methods of the nested anonymous structure, that is, the fields and methods with the first letter in uppercase or lowercase can be used.

  • Anonymous structure field access can be simplified.

b.A.Name = "tom"b.A.age= 19b.A.Sayok()
b.A.hello()


b.Name = "smith"b.age = 20b.sayok()
b.hello()
  • When the structure and the anonymous structure have the same fields or methods, the compiler uses the principle of nearest access. If you want to access the fields and methods of the anonymous structure, you can distinguish them by the name of the anonymous structure

b.A.age= 19
  • The structure embeds two (or more) anonymous structures. For example, two anonymous structures have the same fields and methods (at the same time, the structure itself does not have fields and methods with the same name). When accessing, you must explicitly specify the anonymous structure Name, otherwise compile an error.

  • If a struct is nested with a named structure, this mode is a combination. If it is a combination relationship, then when accessing the fields or methods of the combined structure, you must bring the name of the structure.

type D struct i
    aA    
}
  • After the anonymous structure is nested, you can also directly specify the value of each anonymous structure field when creating a structure variable (instance)

type Goods struct { 
    Name string 
    Price float64}type Brand struct { 
    Name string 
    Address string}type TV struct { 
    Goods 
    Brand 
}type TV2 struct { 
    *Goods 
    *Brand 
} 

tv := TV{Goods{"电视001",900.99}, Brand{"Haier","Shandong"},} 
tv2 := TV{ 
    Goods{ 
        Price: 88.99, 
        Name :"电视ee2" 
    }, 
    Brand{ 
        Name :"Sharp", 
        Address :"Beijing", 
    }, 
} 


tv3 := TV2{ &Goodsf{"TV03",7000.99},&Brand{"Skyworth","Henan"}} 
tv4 := TV2{ 
    &Goods{ 
        Name :"TV 4", 
        Price: 9eee.99,
    } 
    &Brand{ 
        Name: "Changhong", 
        Address: "Sichuan", 
    }, 
}

Multiple inheritance

If a struct is nested with multiple anonymous structures, then the structure can directly access the fields and methods of the nested anonymous structure, thus realizing multiple inheritance.

In order to ensure the simplicity of the code, it is recommended to avoid using multiple inheritance as much as possible

interface

Polymorphism in Golang is mainly reflected through interfaces

The interface type can define a set of methods, but these do not need to be implemented. And the interface cannot contain any variables. When a certain custom type is to be used, these methods are written (implemented) according to the specific situation.

type Usb interface {
    
    Start()
    Stop()
}
  • All methods in the interface have no method body, that is, the methods of the interface are methods that are not implemented. The interface embodies the idea of ​​polymorphism and high cohesion and low coupling of program design.

  • The interface in Golang does not need to be explicitly implemented. As long as a variable contains all the methods in the interface type, then this variable implements the interface. Therefore, there is no such keyword as implement in Golang

Notes and details

  • The interface itself cannot create an instance, but it can point to a variable (instance) of a custom type that implements the interface

  • All methods in the interface have no method body, that is, they are all methods that are not implemented.

  • In Golang, a custom type needs to implement all methods of an interface. We say that this custom type implements the interface.

  • A custom type can only assign an instance (variable) of the custom type to the interface type if it implements a certain interface

  • As long as it is a custom data type, you can implement an interface, not just a structure type.

  • A custom type can implement multiple interfaces

  • There cannot be any variables in the Golang interface

  • An interface (such as A interface) can inherit multiple other interfaces (such as B and C interfaces). At this time, if you want to implement the A interface, you must also implement all the methods of the B and C interfaces.

  • The interface type is a pointer (reference type) by default. If it is used without initializing the interface, it will output nil

  • The empty interface interface} has no methods, so all types implement the empty interface, that is, we can assign any variable to the empty interface.

The difference between inheritance and interface

  • When the A structure inherits the B structure, then the A structure automatically inherits the fields and methods of the B structure, and can be used directly

  • When the A structure needs to expand its functions, and does not want to destroy the inheritance relationship, you can implement an interface. Therefore, we can think that the implementation of the interface is a supplement to the inheritance mechanism.

Implementing an interface can be seen as a supplement to inheritance

Interface and inheritance solve different problems

  • The value of inheritance is mainly to solve the reusability and maintainability of the code.

  • The value of the interface mainly lies in: design, design various specifications (methods), and let other custom types implement these methods.

  • Interface is more flexible than inheritance

  • Interfaces are more flexible than inheritance,

    • Inheritance is to satisfy the is-a relationship

    • The interface only needs to satisfy the like-a relationship

  • The interface achieves code decoupling to a certain extent

Polymorphism

Variables (instances) have many forms. The third major feature of object-oriented, in the Go language, polymorphism is achieved through interfaces. Different implementations can be called according to a unified interface. At this time, the interface variable takes a different form.

  • Polymorphic parameter

  • Polymorphic array

Type assertion

Type assertion, because the interface is a general type, you don't know the specific type, if you want to convert to a specific type, you need to use type assertion

var x interface{}var b2 float32 =1.1x=b2     
        
y := x.(float32) 
fmt.Printf("The type of y is the lamp value =%v", y, y)

When making a type assertion, if the type does not match, it will report panic. Therefore, when making a type assertion, make sure that the original empty interface points to the asserted type.

var x interface{}var b2 float32 =2.1 x = b2if y, ok := x.(float32);ok { 
    fmt.Println(" convert success") 
    fmt.Printf("The type of y is %T and the value is =% v",y, y) 
}else { 
    fmt.Print1n(" convert fai1") 
} 
fmt.Print1n("Continue execution...")

 

 

Guess you like

Origin blog.csdn.net/ThomasYC/article/details/115214890