简体   繁体   中英

Is it good, that every PHP class implements a Singleton pattern

is it good, that every PHP class implements a Singleton pattern? I think, it will be less memory usage because of it. Is it right opinion? Thanks!

Software is meant to model the reality. that's the way the OOP exists. that said, Singleton is not a hammer for all nails. You can use it in certain models, but there are others which simply will not adjust.

Take for example, model a list of persons. If you decide to create a Person class, then you will not be allowed to have more than one person on your model.

If all your classes are singletons, why use classes?

Singletons are useful in some cases, but tend to be over-used. If you can get away with singletons, then you probably don't need classes for their intended object-oriented uses. They can still be useful for code modularization, though.

In general, classes are most useful when you do have multiple instances of the class. Classes are blueprints for objects, so you can create many objects with similar behavior but, typically, different internal state.

So, if all your classes are Singletons, I would step back and ask a couple questions:

  • Do you need classes?
  • Are you thinking correctly about how your software models the problem you're trying to solve?

There is a simple rule: If it's definitly sure that a class is only to be used once, implement Singleton. If it needs to be used more than once, don't do it.

If your programm has only classes with one single instance it looks like a major code smell and is not suitable for object-oriented programming.

This seems like a very bad idea. I would recommend keeping any data you need between requests in a session (if per user) or a cache (if per server). As far as memory usage, it should not make that much of a difference.

Actually it is (combined with factory), take Kohana 3 Framework for example;

it uses singleton / factory combination where ever it's possible.

It is possible, it just would not be OOP design. OOP is meant to simplify structing with 3 main properties: inheritance (ie common classes share the same interface), polymorphism (ie subclassing) and encapsulation (ie having a blackbox approach to your objects).

Singleton, although they can be extended and abstracted, usually aren't so that basically takes OOP goodies out of your reach. It would be some sort of original procedural programming with everything namespaced in global scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM