doucanshou6998 2012-02-17 07:31
浏览 38
已采纳

工厂模式可以是通用的Singleton吗?

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?

  • 写回答

1条回答 默认 最新

  • dongtiaozhou4914 2012-02-17 07:58
    关注

    No, it isn't. What you are describing would be a special use case of the factory pattern or not a factory at all. A simple factory doesn't do 'instance management', it just returns a new instance of the needed concrete subclass.

    The fact that the factory method itself is static, doesn't mean that the methods of the returned subclass are. A factory, as the name says it, produces concrete objects with non-static functionality.

    http://sourcemaking.com/design_patterns/factory_method

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突