Go language object oriented programming

Posted by raja9911 on Fri, 21 Jan 2022 01:11:10 +0100

1, Object oriented and process oriented

  • Process oriented programming code is only applicable to the current situation, while object-oriented programming pays more attention to reuse. The same set of code can be used in various situations
  • Process oriented programming (OPP) is to implement the whole process in order in detail
    • For example, when students go to school from home, they need to go out – > find OFO – > scan and unlock – > get in the car – > go straight – > turn left – > find "congee cake noodles" – > stop – > lock – > open the door – > find seats – > order Shandong pancakes and Sichuan hot pot – > serve – > eat – > pay in cash – > go out – > find OFO
  • Object oriented programming (OOP) is all about objects. Objects have their own behavior and characteristics. In the process of programming, data and business are encapsulated, the same type of content is inherited, and the same code realizes various effects, so as to realize high availability and high reuse programs Three basic characteristics of traditional object-oriented: encapsulation, inheritance and polymorphism
  • For example, after walking out, walking or bus or driving or sharing any brand share the bicycle as long as it can go to the place where you eat. You can fill your stomach any time you eat. You can choose what dishes to eat. You can choose not only Shandong pancakes and Sichuan hot pot. After paying for the meal, you can pay for Alipay, Alipay, and credit card besides cash payment. Just go home after dinner

2, Object oriented in Go language

Object oriented is a kind of thought. So far, there is no very clear definition. Old programmers have different understanding of object-oriented in different periods Go language has its own understanding of object-oriented

Although there is no universally accepted definition of object-oriented programming, for our purposes, an object is simply a value or variable that has methods , and a method is a function assiociated with a particular type.

  • It can be seen from the above explanation that go language developers believe that object-oriented means that a specific type (structure) has its own method. Using this method to complete object-oriented programming does not mention encapsulation, inheritance and polymorphism When all go languages carry out object - oriented programming, the focus is on the flexible use of methods Go language reduces the pressure of language learning through this design
  • Go language has its own understanding of object-oriented, and it also has its own encapsulation, inheritance and polymorphism

3, Encapsulation

  • Encapsulation is mainly reflected in two aspects: encapsulating data and encapsulating business
  • In Go language, access is controlled by the size of the initial letter The first letter of the attribute is lowercase. Providing access methods to the outside world is the most common implementation of encapsulating data
  • Business can be encapsulated by methods
    • The proposed method is encapsulation
    • Control structure attribute access, and provide external access methods is also encapsulation
  • Benefits of encapsulation in object orientation:
    • Safety Structure attribute access is restricted and must be based on specific access channels
    • Reusability, packaging method to achieve reusability
    • Read and write, multi segment to increase code readability

code implementation

  • Go language can access the global content anywhere in the same package, and encapsulation control can control the access of data in the structure outside the package
type People struct {
	name string //full name
	age  int    //Weight Unit Jin
}

func (p *People) SetName(name string) {
	p.name = name
}
func (p *People) GetName() string {
	return p.name
}

func (p *People) SetAge(age int) {
	p.age = age
}

func (p *People) GetAge() int {
	return p.age
}

Encapsulating business is to extract code according to your own needs, and encapsulate business (code) with attributes using the function process in the Go language standard library

4, Inherit

  • According to the traditional object-oriented idea, inheritance is to put forward the common ground of the same kind of things as the parent class, so that the child class can reuse the accessible content of the parent class
  • Inheritance can be implemented in many ways
    • Strong coupling implementation through keyword inheritance
    • Combinatorial inheritance, loosely coupled inheritance
  • Those who have used java or C # should know to use combination instead of inheritance as little as possible. High cohesion and low coupling can be used The father of Java also said in an interview that if he was given a chance to make Java again, what he most wanted to modify was inheritance
  • Inheritance in Go language is realized through composition

Anonymous properties

  • Anonymous attributes (attribute names in structs) are supported in Go language, but each can only have anonymous attributes at most The compiler thinks that a type is an attribute name. When we use it, we use it as an attribute name
type People struct {
	string
	int
}

func main() {
	p:=People{"smallming",17}
	fmt.Println(p.string,p.int)
}

Relationship between structures

  • The relationship between classes in traditional object-oriented
    • Inheritance: is-a, strong coupling. It is generally believed that there is a strong relationship between classes
    • Implementation: like-a, the relationship between interfaces and implementation classes
    • Dependency: use-a is accidental, temporary and very weak, but the change of class B will affect a, which is generally used as a method parameter
    • RELEVANCE: has-a is a strong dependency, such as me and my friends; This relationship is stronger than dependence, there is no contingency of dependence, and the relationship is not temporary. It is generally long-term, and the relationship between the two sides is generally equal, and the relationship can be one-way and two-way
    • Aggregation: has-a, the relationship between whole, part and ownership
    • Combination: contains-a, which embodies the relationship of contains-a, which is stronger than aggregation, also known as strong aggregation; It also reflects the relationship between the whole and part, but at this time, the whole and part are inseparable. The end of the whole life cycle means the end of the part life cycle
    • Combination > aggregation > Association > dependency
  • Standard combination relation in Go language
type People struct {
	name string
	age  int
}

type Teacher struct {
	peo       People
	classroom string //class
}

func main() {
	teacher := Teacher{People{"smallming", 17}, "302 classroom"}
	//The contents of another structure must be called by the contained variable name
	fmt.Println(teacher.classroom, teacher.peo.age, teacher.peo.name)
}

Use anonymous attributes to complete inheritance in the Go language

  • Inheritance in Go language is well implemented. Taking another structure type as an attribute of another structure, you can directly call the content of another structure
  • Because the structures in Go language cannot be converted to each other, the child structure variable cannot be assigned to the parent structure variable
type People struct {
	name string
	age  int
}

type Teacher struct {
	People
	classroom string //class
}

func main() {
	teacher := Teacher{People{"smallming", 17}, "302 classroom"}
	fmt.Println(teacher.classroom, teacher.age, teacher.name)
}

5, Interface

  • Interface interpretation: an interface is the definition of a set of behavior specifications
  • There can only be method declarations in the interface. Methods can only have names, parameters and return values, and cannot have method bodies
  • There can be multiple method declarations in each interface. After the structure rewrites all the methods in the interface, the structure belongs to the interface type
  • The relationship between interface and structure in Go language is the relationship of is-like-a in traditional object-oriented
  • The keyword defining the interface type is interface
type Interface name interface{
  Method name(parameter list) Return value list
}

The interface can inherit the interface, and Go language recommends splitting the methods in the interface into multiple interfaces

Code example
After declaring the method in the interface and writing the method in the interface, the compiler considers that the structure implements the interface

  • The overridden method must be exactly the same as the method name, method parameters (parameter names can be different) and return value list in the interface
type People struct {
	name string
	age  int
}

type Live interface {
	run(run int)
}

func (p *People) run(run int) {
	fmt.Println(p.name, "Running,Run away,", run, "rice")
}

func main() {
	peo := People{"Zhang San", 17}
	peo.run(100)
}

If there are multiple method declarations in the interface, the interface body must override all the methods in the interface before the task structure implements the interface

type People struct {
	name string
	age  int
}

type Live interface {
	run(run int)
	eat()
}

func (p *People) run(run int) {
	fmt.Println(p.name, "Running,Run away,", run, "rice")
}
func (p *People) eat() {
	fmt.Println(p.name, "I am eating")
}

func main() {
	peo := People{"Zhang San", 17}
	peo.run(100)
}

Interfaces can inherit interfaces (combinations), and the above code can be rewritten into the following code

type People struct {
	name string
	age  int
}

type Live interface {
	run(run int)
	Eat
}

type Eat interface {
	eat()
}

func (p *People) run(run int) {
	fmt.Println(p.name, "Running,Run away,", run, "rice")
}
func (p *People) eat() {
	fmt.Println(p.name, "I am eating")
}

func main() {
	peo := People{"Zhang San", 17}
	peo.run(100)
}

6, Polymorphism

  • Polymorphism: the same thing has different results due to different conditions
  • Because the structures in Go language cannot be converted to each other, there is no polymorphism of structures (parent-child structures), only interface based polymorphism This is also in line with the object-oriented interpretation of Go language
  • One of the most common ways of polymorphism at the code level is to treat interfaces as method parameters
  • When the structure implements all methods of the interface, it is considered that the structure belongs to the interface type, which means that the structure variable can be assigned to the interface variable
  • When rewriting an interface, the receiver is the difference between Type and * Type
    • *Type can call * type and type as receiver methods Therefore, as long as there is at least one method rewritten with * type as the receiver in multiple methods in the interface, the structure pointer must be assigned to the interface variable, otherwise the compilation will report an error
    • Type can only call methods with type as the recipient
type Live interface {
	run()
	eat()
}
type People struct {
	name string
}

func (p *People) run() {
	fmt.Println(p.name, "Running")
}
func (p People) eat() {
	fmt.Println(p.name, "be at  table")
}

func main() {
	//When overriding an interface
	var run Live = &People{"Zhang San"}
	run.run()
	run.eat()
}

Since the interface can receive structural variables that implement all methods of the interface, the interface can also be used as method (function) parameters

type Live interface {
	run()
}
type People struct{}
type Animate struct{}

func (p *People) run() {
	fmt.Println("People are running")
}
func (a *Animate) run() {
	fmt.Println("Animals are running")
}

func sport(live Live) {
	fmt.Println(live.run)
}

func main() {
	peo := &People{}
	peo.run() //Output: people running
	ani := &Animate{}
	ani.run() //Output: animals running
}

Topics: Go