Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2009ACS-3913 R McFadyen1 Singleton Problem: Exactly one instance of a certain object is required (this object is called a singleton). We must ensure.

Similar presentations


Presentation on theme: "Fall 2009ACS-3913 R McFadyen1 Singleton Problem: Exactly one instance of a certain object is required (this object is called a singleton). We must ensure."— Presentation transcript:

1 Fall 2009ACS-3913 R McFadyen1 Singleton Problem: Exactly one instance of a certain object is required (this object is called a singleton). We must ensure a class has only one instance. Solution: use a static method of the class to return the singleton Factories and Facades are usually singletons. Textbook problem: how do we control the instantiation of the ServicesFactory? Singleton Pattern

2 Fall 2009ACS-3913 R McFadyen2 Singleton In Java, you would have code such as: Public static synchronized ServicesFactory getInstance() { If (instance == null) Instance := new ServicesFactory() Return instance } Singleton Pattern The point of the above is that only one instance is ever created. If one already exists, then the create is bypassed and the reference to the existing object is returned.

3 Fall 2009ACS-3913 R McFadyen3 Singleton In Java, you would have code such as: Public static synchronized ServicesFactory getInstance() { If (instance == null) Instance := new ServicesFactory() Return instance } Singleton Pattern The “synchronized” keyword ensures that only one “thread” runs this code at a time. The text refers to a “critical section”.

4 Fall 2009ACS-3913 R McFadyen4 Singleton Pattern Suppose an instance of the ServicesFactory is created and, later on, a message, getTaxCalculatorAdapter(), is passed to this instance. :Register :ServicesFactory getInstance() ServicesFactory new() getTaxCalculatorAdapter()

5 Fall 2009ACS-3913 R McFadyen5 Singleton Pattern :Register :AccountingAdapter getAccountingAdapter() > :ServicesFactory new() post() By applying the > stereotype to this object, they are implying that the getInstance method was used to instantiate it.

6 Fall 2009ACS-3913 R McFadyen6 Singleton Pattern The text makes reference to Lazy Instantiation – The ServicesFactory object was created when it was needed, and not before :Register :AccountingAdapter getAccountingAdapter() > :ServicesFactory new() post()

7 Fall 2009ACS-3913 R McFadyen7 Patterns Quote from text “To handle the problem of varying interfaces for external services, let’s use Adapters generated from a Singleton Factory” :Register :AccountingAdapter getAccountingAdapter() > :ServicesFactory new()...


Download ppt "Fall 2009ACS-3913 R McFadyen1 Singleton Problem: Exactly one instance of a certain object is required (this object is called a singleton). We must ensure."

Similar presentations


Ads by Google