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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分