Introdication To Design Patterns Singltone Design Pattern
Introdication To Design Patterns Singltone Design Pattern
Design Pattern
Design Patterns
What is a Design Pattern?
Types
Erich Gamma, Richard Helm, Ralph Johnson and John Vlisides in
their Design Patterns book define 23 design patterns divided into three
types:
► Creational patterns are ones that create objects for you, rather than
having you instantiate objects directly. This gives your program
more flexibility in deciding which objects need to be created for a
given case.
► Structural patterns help you compose groups of objects into larger
structures, such as complex user interfaces or accounting data.
► Behavioral patterns help you define the communication between
objects in your system and how the flow is controlled in a complex
program.
Java Design Patterns
Creational Patterns
► The creational patterns deal with the best way to create instances of
objects.
► In Java, the simplest way to create an instance of an object is by
using the new operator.
Fred = new Fred(); //instance of Fred class
► This amounts to hard coding, depending on how you create the
object within your program.
► In many cases, the exact nature of the object that is created could
vary with the needs of the program and abstracting the creation
process into a special “creator” class can make your program more
flexible and general.
Java Design Patterns
The Singleton pattern ensures a class has only one instance, and provides a
global point of access to it.
The class itself is responsible for keeping track of its sole instance. The class
can ensure that no other instance can be created (by intercepting requests to
create new objects), and it can provide a way to access the instance.
Singletons maintain a static reference to the sole singleton instance and return a
reference to that instance from a static instance() method.
The Singleton Pattern
The Classic Singleton - I
protected ClassicSingleton() {
// exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
The ClassicSingleton class maintains a static reference to the lone singleton
instance and returns that reference from the static getInstance() method.
The Singleton Pattern
The Classic Singleton - II
...
The Singleton Pattern
Problems - I