Monday, November 16, 2015

Head First Design Pattern CH5: Singelton Patterns

1- example of objects that could be singlton: Thread pool, cache, dialog boxes, logging,

this is a simple example, private constructor and getInstance() method

2- the previous example has concurrency issue, to fix it:

we made getInstance synchronized.

3- the previous example fixes the issue, however there is an overhead because of the synchronize, we every time the getInstance() is called we need extra resource to make it synchronize eventhough we need the syncronization only when we create the instance for the first time.

4- to fix the synchronization overheard, create the instance directly, JVM will be sure that the instance is created before any thread access it.

5- or you can synchronize the creation only

6- Be careful, if you have multiple class loaders then you can load the singleton class multiple times, which means you will have multiple instances of it.

7- as you can see the Singleton class actually does multiple things, it is responsible for its creation in addition to the actual behavior, it is OK, you can think of a solution like Singleton Factory:

8- forget about Singleton subclassing, the constructor is private so basically you cannot extend it, dont do a work around, think about your design again

No comments:

Post a Comment