Prototype Design Pattern in Golang

Hi friends! With you, Alex and I continue our series of articles on the use of design patterns in the Golang language .





It is interesting to receive feedback from you, to understand how applicable this area of ​​knowledge is in the world of the Golang language . We have already looked at templates: Simple Factory , Singleton and Strategy . Today I want to consider another design pattern - Prototype .





What is it needed for?

It is a generative design pattern that allows objects to be copied without going into the details of their implementation.





What problem does it solve?

Imagine you have an object that needs to be copied. How to do it? Create an empty object of the same class, then copy the values ​​of all fields from the old object to the new one one by one. Fine, but there is a nuance! Not every object can be copied in this way, because part of its state can be private, which means it is inaccessible to the rest of the program code.





There is another problem as well. The copying code will become dependent on the classes of the copied objects. After all, in order to iterate over all the fields of an object, you need to bind to its class. Because of this, you won't be able to copy objects knowing only their interfaces and not specific classes.





What's the solution?

The Prototype template instructs the copying objects themselves to make copies. It introduces a common interface for all objects that support cloning. This allows objects to be copied without being bound to their specific classes. Typically such an interface has only one clone method.





. . , . , , , . , . .





- . , , . -, , . . , , .





Prototype Class Diagram
Prototype Class Diagram

, . - clone. . . , , . , . .





?

, PHP . Prototype Golang.





- . , . ..   , - . , . , - , , .. 





- , . , , , ..





, , prototype



, clone



. struct



, show



clone



prototype



.





, . directory



, prototype



. . show



, clone



. clone



, - , . , _clone



.





. . , . :





Open directory 2
  Directory 2
    Directory 1
        category 1
    category 2
    category 3


Clone and open directory 2
  Directory 2_clone
    Directory 1_clone
        category 1_clone
    category 2_clone
    category 3_clone
      
      



?

  1. . , . , -, . .





  2. . , - , , . . , .





, Prototype :





  • .





  • , .





  • , abstract factory, .





, , . 63% , Golang - . , , , Golang - . , . , , .





, , . .

!








All Articles