P
P
Pavel Belyaev2019-04-16 18:45:24
Programming
Pavel Belyaev, 2019-04-16 18:45:24

How to understand factory method?

Hello, sorry if my question seems too stupid, the fact is that I have been programming for a relatively long time, in the process of reading the book I understand that I already use some patterns or something similar to them, but now I wanted to read some literature, so to speak, in order to rethink some points . And then I stumbled on the factory pattern, I figured out the simple factory, but not quite with the factory, too long, tedious and stretched out ...
Correct me if I misunderstood, but I'll tell you how it was deposited in my head ...
1 There is a certain class, one of whose methods is to create an instance of the object with which we will work

abstract class Myclass
{

  public function prepare($type)
  {
    $newclass = $this->create_class($type);
    $newclass->get();
    $newclass->prepare();
    return $newclass->get_result();
  }

  protected function create_class($type)
  {
    //это будет в субклассах
  }
}

And then subclasses override the moment of object creation
class Subclass extends Myclass
{
  protected function create_class($type)
  {
    if ($type===1) return new Class1;
    if ($type===2) return new Class1;
    ...
  }
}

Am I understanding correctly or is there something wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Romashkan, 2019-05-12
@EvgeniiR

Try to understand the purpose and patterns, memorizing implementations is almost pointless. An abstract factory creates an object of a particular type, not a class, of course.
A factory is a special case of implementing dependency inversion. The profit of inversion is huge - it allows stable modules not to depend on unstable ones, for example, from input devices.
I can recommend Uncle Bob's Clean Architecture as food for thought

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question