Go core development study notes (Niansan) - object-oriented programming, factory mode

Object-Oriented Programming

The basic steps Comparative python

  1. Statement structure, the structure is determined to confirm the name of a class name //: Class xxx ():
  2. // determine the field structure of the class attribute confirmation: DEF the init
  3. The method of preparation of structure confirmed // class methods: def xx ():

The most simple example: write a player structure, containing name string, gender string, age int, num int, ability float64 field; write a method that returns the player all the information after the call

package main
import "fmt"
type player struct {
	name string
	gender string
	age int
	rolenum int
	ability int
}

func (p *player) callback() string {
	res := fmt.Sprintf("定义球员信息如下:\n姓名:%v\n性别:%v\n年龄:%d\n球衣号码:%d\n能力值:%d\n",p.name,p.gender,p.age,p.rolenum,p.ability) //定义字符串打印的可以传递变量
	return res
}

func main() {
	var p1 *player = &player{"durant","male",30,35,94}   //后续工程中优秀做法是把结构体指针返还给变量,因为指针传递值很小,效率高
	res := p1.callback()
	fmt.Println(*p1)      //由于var是一个指针,所以当查看实例的时候前面会加一个&符,去掉只需要打印*p1取值即可
	fmt.Println(res)
}

Golang no constructor, using the factory pattern to solve the problem

A non-main package defines a struct, but the first letter lowercase, struct field is lowercase, want to call the structures and fields in main (), in general, can not be completed, select the factory pattern to solve.

A conventional way to write the package can not be imported:

package utils                //创建一个utils包

type students struct {       //这个结构体是小写,无法用于其他包导入     
	Name string
	Age int
	score float64            //这个结构体的字段是小写,无法用于其他包导入
}

func Student(n string,a int) *students {    //写一个方法,装饰一下,方法本身首字母大写,所以可以被其他包导入,解决结构体小写问题
	return &students{                       //传递参数和结构体字段一模一样,返回值是结构体指针变量,存放在堆中,共享的,大家都可以使用
		Name : n,
		Age : a ,
	}

func (s *students) Getscore() {             //写一个方法,装饰一下,方法本身首字母大写,所以可以被其他包导入,解决结构体字段小写问题
	return (*s).score	                        //直接将utils函数中的score返回给一个首字母大写函数,在main包中再调用这个函数获得值
}

Utils package introduced in the main function:

package main
import (
	"fmt"
	"utils"
)

func main() {
	var stu = utils.Student("zhaolu",20)    //使用函数传递两个参数,stu接收函数的返回值也是一个指针
	fmt.Println(*stu)                       //为了查看字段值,需要用取值符取得变量。
	fmt.Println(stu.Getscore())             //这样就可以访问私有字段了
}

Object-oriented programming ideas - Abstract

  1. First is that their point of view, if learned k8s must find the essence of the whole k8s is abstract (Abstraction), resource pool abstract various types of resources -> Kind, Google family of products, naturally reflected in the Golang.
  2. The common properties and methods of a class of things is extracted form a physical model, this approach research questions called abstract.
  3. Create a model: the development of a system of bank accounts, properties: name, account number, balance, method: withdrawal, transfer, balance inquiry and so on.
  4. Object-oriented three characteristics: encapsulation, inheritance, polymorphism, different Golang implementation, the weakening of the way, and not to other OOP languages ​​were forced compare.

Package encapsulation:

  1. The operation of the abstract packaging fields and field together, within the data to be protected, other program packages only, for the field can be operated by the authorized operator.
  2. Packaging can hide implementation details, data validation, ensure the safety of rationality.
  3. Golang package is the above-described embodiment, the packet structure field on the lower case, by controlling other lowercase import the package to improve safety of the operation of the factory control mode field.

Package implementation steps

  1. The first letter lowercase structure, field (not export, and import other packages can not use, similar to java's private).
  2. Where the package provides a factory pattern to the structure function of the first letter capitalized, similar to a constructor (set for permission to call another package structure).
  3. A capitalized Set method (similar to java's public), is used to determine the properties and assignments (field structure is set for permission to call other packages).
    The third highlights, increase in the Set method, and business logic may be restrictions on the range of values is called a field structure, must follow the restrictions on other process conditions Set recall packet structure field.
    Or increase the Get method, or a return value of the desired field, required in main () receiving the corresponding variable.

For example: data desensitization can be done to establish a Person structure, can not guarantee direct access to age, first create a demo package

package demo
import "fmt"
type person struct {
	Name string
	age int
}
func Person(n string) *person {        //因为Name字段为大写,所以只需要通过工厂模式提供的Person函数就直接访问
	return &person{
	Name : n,
	}
}
func (p *person) SetAge(age int) {     //因为age字段为小写,所以需要构造方法,提供设置和访问方法,不可以直接使用<引入包结构体变量>.<结构体字段>的方式使用
	if age > 0 || age < 150 {
		p.age = age
	} else {
		fmt.Println("输入的年龄不符合要求,默认为18岁")
		p.age = 18
	}
}
func (p *person) GetAge() int {
	return p.age
}

Use in main () methods set and get and set calls, can not be used directly <introduced into the package structure variables> <field structure> manner using

package main
import (
	"demo"
	"fmt"
)
func main() {
	var p = demo.Person("马云")
	p.SetAge(50)
	fmt.Println(p.GetAge())
	fmt.Println(*p)
	fmt.Println(p.Name)
}

inherit:

  1. Extracting common attributes and methods of different structures, written in a new structure the same attributes and methods defined, parent class does not exist Golang in subclass.

  2. By embedding an anonymous structure, complete loosely coupled.

  3. Inherited advantages: improved code reuse; scalability and maintainability of the code improves.

    There are examples of references and attributes:

    type Students struct {          //定义一个共有结构体属性:学生,学生一定都有姓名,年龄和学号
    	Name string
    	Age int
    	SerialNo int
    }
    
    type Xiaoxuesheng struct {
    	Students          //定义一个结构体是小学生,引入共有结构体属性,也就拥有了姓名,年龄和学号
    	angery string     //小学生有一个独有属性:小学生之怒,如果需要引入其他结构体,除了共有属性之外,自由定义独有属性
    }
    

There are exemplified methods and references:
FUNC (STU * Students) <method name> () {..., stu.Name , such stu.Age} // This method can also be used in other structures embedded in the Students structure.

There is a structure attribute field assignment:
<new structure name> <structure common attributes> <common attributes structure field> // example, students define the name,.. Xiaoxuesheng.Students.Name = "Chun"
use methods a total of structure:
. <new structure name> <structure common attributes> <common attributes method name> () // method such as increasing a total exam, examing (), primary school exam Xiaoxuesheng.Students.examing ( )

In-depth discussion of inheritance

  1. The new structure can use nested all fields and methods of anonymous structures, namely the first letter capitalized or lowercase fields, methods, can be used, is limited to a .go file, import the other does not go try.

  2. Simplified wording, for example, when the definition and use fields, can be directly omitted hierarchical structure of common attributes:
    <new structure name> <structure common attributes> <field structure common attributes> == <name of the new structure. >. <common attributes structure field> // Xiaoxuesheng.Name = "Chun"
    <new structure name>. <common attributes structure>. <common attributes method name> () == <new structure name>. <method common attributes name> () // Xiaoxuesheng.plusbuff () = " vested body care"

  3. If you have the same name as the field names and field a total of structure in the new structure, then it will not adopt <new structure name>. <Common attributes structure field>, but <new structure name> <new structure field>, so the match in accordance with the rules specified field once found, be sure to select the most qualified first outer layer of a field name, that is, the principle of proximity, it is in line with A. <field> will not find AB <field>.

  4. When Similarly, if a new structure is embedded in a total of two structures, there are two structures have the same field names, the new structure using C. <total field>, the compiler will complain, this time must be specified anonymous structure name to show assignment, CAName = "dog" CBName = "cat", directly c.name = "xx" inevitable error, the method for the same reason.

  5. Understand the relationship anonymous structures and combinations of structures: If a combination of the structure, then it is not inherited, and this time can not be selected to simplify the writing, and must use the BA <field> = "xx"
    exemplified:
    (. 1) type A struct {...} type B struct {A ...}: anonymous structure can be simplified, BA <A field> == B. <A field> bAName == b.name
    (2) type A type struct {...} B struct {a A ...}: combination structure, can not be simplified, BA <A field> = B. <A field>! baName = "XX"

  6. Or a combination of inheritance, the definition of variables can be used directly nested assignment, if needed nested C A, B two anonymous structures, pointers may be passed struct {C type A \ n- B}, so that transfer efficiency is more high.
    If the value, must write * cA <field> is an entire address.

  7. Multiple inheritance: not recommended, multiple inheritance if different anonymous structure has the same field, you must specify the <anonymous structure name> <field name> This hierarchy is equivalent to using a different namespace provide the same field.

Multi-state
study done interfaces to say, polymorphism is achieved mostly through the interface Interface

Published 49 original articles · won praise 18 · views 4004

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/90169862