开发者

Pure Static Class vs Singleton

开发者 https://www.devze.com 2023-02-26 04:04 出处:网络
Writing a PHP app and have several classes that only have static methods (no need for instance methods). An example of one is NumericValidator, which has methods like checkInteger($toCheck) which chec

Writing a PHP app and have several classes that only have static methods (no need for instance methods). An example of one is NumericValidator, which has methods like checkInteger($toCheck) which checks to make sure the argument you pass it is of type int, and checkGreaterThan($lOperand, $rOperand), which makes sure that the left operand is greater than the right operand, etc.

I know I could just throw each of these methods into a PHP file without putting them inside of a class, but I want to take an OOP approach here in case the API evolves to require instantiating NumericValidator.

But it does beg the question: how is a class with 100% static methods any different than have a class implement a singleton design pattern, where every reference used throughout the code base invokes the same instance?

For example, here is what my code looks like now:

public function doSomething($p_iNum)
{
    if(!NumericValidator::checkInteger($p_iNum))
        // throw IllegalArgumentException

    // ...
}

But I could turn all of NumericValidator's static methods into non-static instance methods, forcing the programmer to instantiate it, and then implement a singleton design pattern so you can only ever reference 1 instance of it:

public function doSomething($p_iNum)
{
    NumericValidator $nv = NumericValidator::getInstance();

    if(!nv->checkInteger($p_iNum))
        // throw IllegalArgumentException

    // ...
}

Finally, my question: which is better and more in keeping with best practices? Are there performance considerations? How would ei开发者_C百科ther approach affect things like concurrency, or requests coming from multiple users?


I would use a static class in your example. The differentiator I would use is if there is any state of the properties of an instance you are trying to preserve across access. This is what a singleton is designed for. The static class gives organized access to methods in a namespace which is helpful for clarity in your code but it does not have any properties about itself.

So yes you can use a singleton but it would be bad form because there are no instance properties that you want to make available across page accesses.

Hope this helps.


  1. Use Singleton instead of static class only if you going to pass instance of NumericValidator in variable to some function.
  2. In PHP 5.3 you can get instance of static class:

    class test { public static function instance() { print 'zz'; } }

    $z = new test; $z->instance();

  3. Don't care about concurrency requests in PHP, it's single threaded, each process executes own code.

0

精彩评论

暂无评论...
验证码 换一张
取 消