The prototype pattern

Wiki: The prototype pattern is a type of creation pattern that is characterized by “copying” an existing instance to return a new one, rather than creating a new one. The copied instance is what we call a “prototype,” which is customizable. The prototype pattern is often used to create complex or time-consuming instances, because copying an existing instance makes the application run more efficiently. Or create identical data with different names.

This is a very simple design pattern, and can be seen as cloning method in other languages, such as JAVA/PHP has relevant methods, existing objects from a memory, copy of an identical objects to, for complex object or larger objects, rather than using a variety of design patterns of new objects are much more quickly,

And the stereotype pattern is rarely used alone, but in combination with other objects.

chestnuts

  1. Create a structure

      // Example structure
      type Example struct {
      	Content string
      }
    Copy the code
  2. Add clone method

      func (e *Example) Clone(a) *Example {
      	res := *e
      	return &res
      }
    Copy the code

    We copy the value in just one line of code, using the * pointer, directly fetching a copy of the value, and then returning the copy of the value pointer. See the extension below for details.

  3. Write main code

   func main(a) {
   	r1 := new(Example)
   	r1.Content = "this is example 1"
   	r2 := r1.Clone()
   	r2.Content = "this is example 2"
   
   	fmt.Println(r1)
   	fmt.Println(r2)
   
   }
Copy the code

Extended reading: Deep copy and shallow copy

Pass in GO is all about value pass, you pass an object, you pass a copy of the object into a function, you pass a pointer, you pass a copy of the pointer into a function.

When assigning, res:=*e copies the Example object. If it is res:=e, it copies the pointer to the object.

Deep copy is copying the entire object, and shallow copy is copying the object pointer.

For deep copies, go and other languages also often use serialized and deserialized copies:

 func deepCopy(dst, src interface{}) error {
     var buf bytes.Buffer
     iferr := gob.NewEncoder(&buf).Encode(src); err ! =nil {
         return err
     }
     return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
  }
Copy the code

The reflect package is actually used to copy the SERIalization of the GOb package

Note: Golang is passed entirely by value, so if the deep-copied object contains Pointers, these Pointers will be the same after the deep-copied object, resulting in partial data sharing.

At this point, all creative design patterns have been written. You can find other design patterns in the repository below….

The code above is stored in a repository called Golang-Design-Patterns

Go web framework bingo, for star, for PR ~