Factory Method Pattern

Hi friends. Alex Versus with you





Earlier we talked about the Singleton and Strategy design patterns , about the subtleties of implementation in the Golang language .





Today I will tell you about the Factory method. 





What's the point?

The Factory method, also known as the Virtual Constructor, is an astounding design pattern that defines a generic interface for creating objects in a parent class and allows the created objects in child classes to be modified. 





The template allows a class to delegate object creation to subclasses. Used when:





  1. The class does not know in advance which objects of which subclasses it needs to create.





  2. Responsibilities are delegated to the subclass, and knowledge of which subclass takes on those responsibilities is localized.





  3. Created objects of the parent class are specialized in subclasses.





What problem does it solve?

Imagine you have created a food delivery management program. The program uses an electric scooter as the only delivery vehicle. Your e-scooter couriers deliver food from point A to point B. It's simple. 





. , , -. . .





, , 80% . ? 





, , , .





?

. , . , : . , .





, , , .





, . , , , . 





.





Factory Method class diagram
Factory Method

Golang

PHP, . Golang , , . , - .





iTransport.go,   . (struct), iTransport.





Factory.go, . main.go. getTransport(t string)



, . 





?

  1. . , , . 





  2. . , . , .





?

  1. . , .





  2. .





  3. / (. open–closed principle, OCP) — , : « (, , . .) , »





?

, .





, -. 





, Alex Versus. .

!








All Articles