Singleton

来源:互联网 发布:java缓存技术 ecache 编辑:程序博客网 时间:2024/06/07 02:23

Book List:
1. Design_Patterns For Dummies
2. DesignPatterns-Elements of Reusable Object-Oriented Software-1995
3. Software Architecture Design Patterns in Java-2004
4. DesignPatternJavaWorkbook-Steven John Metsker-2002
5. Java Design Patterns A Tutorial (James W. Cooper)
6. design_pattern tutorialsPoint


- 1. database objects: one is enough. How are you going to avoid creating a new object each time someone uses the new operator on your class? make the constructor private. That stops anyone’s code from using the new operator, except for the code inside the Database class. Then use a utility method getInstance(){

if (singleObject == null){ singleObject = new Database(n);}
return singleObject;
}
Singleton vs Flyweight: The Singleton pattern lets you make sure that no matter how many times your code tries to create an object from a specific class, only one such object is created. That’s important in case you’ve got an object that is so sensitive that conflicts just can’t be tolerated, such as an object named, say, windowsRegistry. Using the Singleton pattern lets you take con- trol over the object instantiation process away from the new operator.
The Flyweight pattern is similar to the Singleton pattern. Here, however, the idea is that if your
code uses many large objects — using up system resources — you can fix things by using a smaller set of template objects that can be configured on-the-fly to look like those larger objects. The configurable objects — the flyweights — are smaller and reusable (so there are fewer of them), but after being configured, they will appear to the rest of your code as though you still have many large objects.


 - 3. Use case: only a single instance of the class is sufficient. For example, we may need a single database connection object in an application. it ensures that there exists one and only one instance of a particular object ever. 
0 0