Isn't factory a general singleton? Or may the Factory pattern be Singleton sometimes? Let's assume we have the following Factory pattern class:
abstract class Factory {
/* This cache contains objects that has already been called.
** It stores the class name, arguments and the object itself.
** If an another call for the same class with the same arguments
** is made we return the object.
*/
private static $cache;
public static function __callStatic($class, $args) {
// 1) we check if the class already exists in the cache
// 2) if it does then we return the object in the cache
// 3.1) otherwise we create a new object
// 3.2) we pass to the constructor of that object the arguments with ReflectionClass
// 3.3) we store the class name, arguments and object in the cache
}
}
And a concrete class
class My extends Factory {}
And let's assume we have a class DontKnow($arg1, $arg2)
that accept arguments $arg1
and $arg2
to the constructor. And let's assume we have another class DoNot()
that doesn't accept any parameter to the constructor.
Now when we call
My::DontKnow('sample', 3);
we return an object that is now stored inside the cache of our factory class. If we call it again our factory class will not instantiate a new object, but will use the same again.
So for example if we set My::DontKnow('sample', 3)->setSomething('key', 'myvalue');
and inside another scope we call My::DontKnow('sample', 3)->getSomething('key');
it will print myvalue
.
But if we call My::DoNot()
the factory class will return a "singleton" object of the class DoNot() that, since our factory class My
is static, has static scope and can be, then, called everywhere.
Isn't this another example of Singleton? Is this to avoid as well as the Singleton pattern?