nerd
发贴: 42
积分: 0
|
于 2003-05-27 20:58
发信人: NullPointer (空指针·莫之夭阏), 信区: JavaClub 标 题: Singletons rule 发信站: BBS 水木清华站 (Fri Nov 8 20:10:28 2002), 转信 Singletons rule Keep on the object-oriented track with singletons By Tony Sintes Q: I have seen singleton classes used in many places. My question: What is the advantage of using a singleton over a class with static methods? A: The difference between using a singleton over a class with static methods boils down to effective object-oriented design. Singletons normally represent a cleaner approach. A class of static methods, unfortunately, breaks down to a simple list of functions, or utilities. Utilities You may ask, what's the problem with a list of functions? Simple. With a list of functions you no longer perform object-oriented programming. In fact, your work easily devolves into a classic procedural program. Suddenly, objects no longer represent the focus of your program. You begin to fall into a data-centric programming mode. That is, instead of sending messages to objects that encapsulate state and behavior, you begin to call functions that act on data. Utilities lead to a clear division between behavior and data that you should never allow in an object-oriented design. That's not to say that you should never use utilities. Object-oriented utilities do exist. There are times that you might need to treat objects as data. For example, I recently wrote a set of utilities that convert Java objects into a CORBA equivalent. It is difficult to turn those methods into a class since they really have no state. I also didn't want to embed the conversion code into the Java classes either. However, it is easy to mess it all up. Singletons Use singletons when you want only one instance of a certain class in your system at any given time. An example could be a class that provides load-balanced access to CORBA servers. You wouldn't want two such objects,
since each would have to get references to the same servers. Grabbing redundant resources would be wasteful. It is better to centralize the server access inside one instance.
|