Presentation is loading. Please wait.

Presentation is loading. Please wait.

What is Singleton Category: Creational pattern

Similar presentations


Presentation on theme: "What is Singleton Category: Creational pattern"— Presentation transcript:

1 What is Singleton Category: Creational pattern
A global object (application-wide visibility) Benefits of static methods + Benefits of objects Concealed object construction process Restrict object creation, and control in a single location

2 How to use Singleton Implementation Details Usage Details
Private constructor ‘getInstance()’ static method ‘instance’ class variable Usage Details Get object via ‘getInstance()’ method instead of constructor.

3 How to use Singleton Traditional Objects A Singleton Object
Implementation public class MyClass { public MyClass() { } public void printMessage(String msg) { System.out.println(message); Usage // create object MyClass m = new MyClass(); // use object m.printMessage(“Hello world!”); A Singleton Object Implementation public class MyClass { private static final MyClass instance = new MyClass(); private MyClass() { } public static MyClass getInstance() { return instance; public void printMessage(String msg) { System.out.println(message); Usage MyClass m = MyClass.getInstance(); m.printMessage(“Hello World”);

4 From (Stephen Stelting, Olav Maassen, Applied Java™ Patterns)
Class Diagram From (Stephen Stelting, Olav Maassen, Applied Java™ Patterns)

5 Why Singleton … instead of single objects
Functionality can be common across application Data can be common across application Actual instance type does not have to be known by developer … instead of static fields/methods Pre-instantiation preparation can be performed (such as constructor code) Access to object-oriented techniques (inheritance, polymorphism, design patterns!) Control of amount and type of instances provided to class users.

6 When to use Singleton Class functionality is useful across application
Different application components share common data sets Memory usage is at a premium Communication must occur between many portable components

7 In the Real World Singletons often serve as common locations for these application services: Logging Data caching/storage Application properties/preferences


Download ppt "What is Singleton Category: Creational pattern"

Similar presentations


Ads by Google