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 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表
  • ¥15 DbVisualizer Pro 12.0.7 sql commander光标错位 显示位置与实际不符