Answer the question
In order to leave comments, you need to log in
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)
{
//это будет в субклассах
}
}
class Subclass extends Myclass
{
protected function create_class($type)
{
if ($type===1) return new Class1;
if ($type===2) return new Class1;
...
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question