Introduction to the

Recently I thought about the business written in the past few years and realized it with process oriented ideas. The reason we use process orientation

One is that people write it that way, and they don’t think much about whether there’s a better implementation

Second, the business is simple, the use of procedural programming can be very convenient to achieve

Third, the business needs to go online quickly, and the process-oriented approach is faster and more direct

However, the disadvantages are also obvious. With the continuous accumulation of business, it is difficult to change the project, and it is necessary to constantly comb out how predecessors wrote and what impact it has. A lot of tests are needed to ensure that the function is normal. Sometimes even similar or iterative requirements do not guarantee fast delivery. And even if it takes a lot of manpower, it’s hard to make sure there are no omissions. This reminds me of the good of object orientation.

Four major features

Object-oriented programming has four main features

  1. Encapsulation features Encapsulation is also called information hiding or data access protection. By exposing a limited access interface, a class authorizes outsiders to access internal information or data only through the means provided by the class. It requires the programming language to provide permission access control syntax to support it, such as the Private, protected, public keywords in Java. On the one hand, the significance of encapsulation is to protect data from arbitrary modification and improve the maintainability of code. On the other hand, only a limited number of necessary interfaces are exposed, improving the ease of use of the class.
  2. Abstract encapsulation is mainly about how to hide information and protect data, while abstraction is about how to hide the concrete implementation of methods, so that users only need to care about the functions provided by methods, and do not need to know how to realize these functions. Abstraction can be implemented through interface classes or abstract classes, but no special syntax mechanism is required to support it. On the one hand, the meaning of abstraction is to improve the extensibility and maintainability of the code, and to reduce the scope of code modification without changing the definition. On the other hand, it is also an effective means of dealing with complex systems, effectively filtering out unnecessary attention to information.
  3. Inheritance features Inheritance is used to represent the IS-A relationship between classes. There are two modes: single inheritance and multiple inheritance. Single inheritance means that a subclass inherits only one parent class, and multiple inheritance means that a subclass can inherit multiple parent classes. In order to inherit this feature, the programming language needs to provide special syntactic mechanisms to support it. Inheritance is mainly used to solve the problem of code reuse.
  4. Polymorphism refers to the fact that a subclass can replace its parent class and call its method implementation during the actual code run. Polymorphism is also a feature that requires the programming language to provide special syntactic mechanisms to implement, such as inheritance, interface classes, and duck-typing. Polymorphism can improve the extensibility and reuse of code, and is the code implementation basis of many design patterns, design principles, and programming skills.

implementation

If you want to use object-oriented programming to implement business logic, you must master how to use the language to implement four features. On the basis of mastering this knowledge, it is possible to flexibly use design patterns to design a good architecture. In the future, when learning a new language, object-oriented implementation needs to be one of the concerns. The following requires a basic knowledge of the Go language.

encapsulation

The implementation encapsulated in Go uses constructs and adds corresponding methods to constructs.

The general implementation steps are as follows:

  1. Lowercase the first letter of a structure or field;
  2. A function that gives the package in which the structure resides a factory pattern, uppercase, like a constructor;
  3. Provide an uppercase Set method (similar to public in other languages) that evaluates and assigns values to attributes.
  4. Provide a uppercase Get method (similar to public in other languages) to Get the value of an attribute.

For example: for employees, age, salary and other privacy can not be checked randomly, and the input age can be reasonably verified. The code structure is as follows

package model

import "fmt"

type person struct {
   Name string
   age  int // Other packages cannot access directly..
   sal  float64
}

// Write a factory-mode function, equivalent to a constructor
func NewPerson(name string) *person {
   return &person{
      Name: name,
   }
}

To access age and sal we write a pair of SetXxx methods and GetXxx methods
func (p *person) SetAge(age int) {
   if age > 0 && age < 150 {
      p.age = age
   } else {
      fmt.Println("Incorrect age range...")
      // Give the programmer a default value}}func (p *person) GetAge(a) int {
   return p.age
}

func (p *person) SetSal(sal float64) {
   if sal >= 3000 && sal <= 30000 {
      p.sal = sal
   } else {
      fmt.Println("Incorrect salary range...")}}func (p *person) GetSal(a) float64 {
   return p.sal
}
Copy the code

There are two things to say about this code

  1. On case
    • Functions starting with lowercase letters are visible only within this package. Functions starting with uppercase letters can be used by other packages. This rule also applies to visibility of types and variables.
    • Case affects visibility. Starting with an uppercase letter equals public, and starting with a lowercase letter equals private. This approach not only eliminates the public and private keywords, but also uniform naming style.
  2. Structure method parameters
    • This can sometimes be an additional cost if the object must be passed by pointer, because the object is sometimes so small (say, 4 bytes) that it is not economical to pass by pointer.
    • You only need to use Pointers if you need to modify objects.

inheritance

The Go language does not support inheritance syntax in object-oriented thinking at all.

On the other side, the Go language also provides inheritance, but uses the grammar of composition, so we call it anonymous composition.

For example:

package main

import "fmt"

type Base struct {
   Name string
}

func (b *Base) SetName(name string) {
   b.Name = name
}

func (b *Base) GetName(a) string {
   return b.Name
}

// implement inheritance
type Child struct {
   base Base // This saves the Base type
}

// Override the GetName method
func (c *Child) GetName(a) string {
   c.base.SetName("modify...")
   return c.base.GetName()
}

// Implement inheritance, but require an external instance of Base
type Child2 struct {
   base *Base // Here is the pointer
}

//
type Child3 struct {
   Base
}

type Child4 struct {
   *Base
}

func main(a) {
   c := new(Child)
   c.base.SetName("world")
   fmt.Println(c.GetName())

   c2 := new(Child2)
   c2.base = new(Base) // Since Base in Child2 is of pointer type, an instance of Base must be provided
   c2.base.SetName("ccc")
   fmt.Println(c2.base.GetName())

   c3 := new(Child3)
   c3.SetName("1111")
   fmt.Println(c3.GetName())

   c4 := new(Child4)
   c4.Base = new(Base)
   c4.SetName("2222")
   fmt.Println(c4.GetName())
}
Copy the code

There are a few things to say about this code

  1. Anonymous and non-anonymous combinations can be used, and if non-anonymous combinations are used, the specified variable name needs to be displayed on the call. If you use an anonymous combination, you don’t need to display the specified variable Name, and you can of course display the call, such as c3.base.name.
  2. In Go, it is also possible to “derive” from a type as a pointer: as in Child4, the Go code still “derives”, but when Child4 creates an instance, it requires an external pointer to the Base class instance.
  3. When “derived” Child3 does not overwrite the member methods of the “Base” class, the corresponding methods are “inherited”. For example, in the above example, calling c3.getName () is the same as calling c3.base.getName (). C. getname () will call the derived method, and if you want to call the Base method, you can display the call.
  4. If a derived class and a base class have the same variable Name, all derived Name members access only the outermost Name variable. The Name variable of the base class is overridden and can be referenced by display.

polymorphism

In Go, a class only needs to implement all the functions required by the interface to be said to implement the interface. If the class implements an interface, you can assign an object instance to the interface.

For example:

package main

import "fmt"

type Money interface {
   show() string
}

type OldMoney struct{}func (oldMoney *OldMoney) show(a) string {
   return "I am old money"
}

type NewMoney struct{}func (newMoney *NewMoney) show(a) string {
   return "I am new money"
}

func PrintMoney(l []Money) {
   for _, item := range l {
      fmt.Println(item.show())
   }
}

func main(a) {
   moneyList := []Money{new(OldMoney), new(NewMoney), new(OldMoney)}
   PrintMoney(moneyList)
}
Copy the code

There are a few things to note about this code:

  1. Interface assignment does not require that the two interfaces be equivalent. If interface A’s method list is A subset of interface B’s method list, then interface B can be assigned to interface A.

  2. The Go language automatically generates a new show() method based on the func (oldMoney oldMoney) show() string function: func (oldMoney oldMoney) show() string Func (oldMoney * oldMoney) show() string

conclusion

Briefly comb the characteristics of Go language, use Go to do object-oriented programming and its simple. Go will be used later to implement 23 design patterns.

data

  1. Understanding and Implementing details encapsulated in the Go language (Golang Classic Programming Case)
  2. Golang inheritance and interfaces
  3. Golang inheritance
  4. The difference between Golang combination and anonymity
  5. 27. Polymorphism of golang

The last

If you like my article, you can follow my public account (Programmer Malatang)

My personal blog is: shidawuhen.github. IO/Review of previous articles:

  1. The Go
  2. MySQL/Redis
  3. algorithm
  4. Architecture/network/project
  5. Think/read notes