33 Javapatterns
33 Javapatterns
Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
[email protected]
www.javapassion.com
Topics
• What is a pattern?
• Why patterns?
• Singleton pattern
• FactoryMethod pattern
• AbstractFactory pattern
• MVC pattern
• Observer pattern
2
What is a Pattern?
What is a Pattern?
4
Why Patterns?
• It solves a problem: Patterns capture solutions, not
just abstract principles or strategies.
• It is a proven concept: Patterns capture solutions
with a track record, not theories or speculation.
• It describes a relationship: Patterns don't just
describe modules, but describe deeper system
structures and mechanisms.
5
Elements Of a Pattern
• Pattern name
• Problem
• Solution
• Consequences
6
List of Common Patterns
Common Patterns
• Singleton
• Factorymethod
• Abstract Factory
• MVC (Model-View-Controller)
• Observer
• Facade
8
Singleton Pattern
Singleton Pattern
10
Singleton Class
public class Singleton {
private static Singleton singleton = new Singleton();
/** A private Constructor prevents any other class from instantiating. */
private Singleton() {
}
/** Static 'instance' method */
public static Singleton getInstance() {
return singleton;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
11
Singleton Pattern Example
public class SingletonPattern {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
System.out.println("Calling a method of a Singleton: " + s1.demoMethod());
Singleton s2 = Singleton.getInstance();
System.out.println("Calling a method of a Singleton: " + s2.demoMethod());
boolean b1 = (s1 == s2);
System.out.println("Object instance s1 and s2 are the same object: " + b1);
}
}
12
FactoryMethod
Pattern
FactoryMethod Pattern
15
FactoryMethod Pattern
16
Abstract Factory
Pattern
Abstract Factory Pattern
• Provides a way to encapsulate a group of individual
factories that have a common theme
• In normal usage, the client software would create a
concrete implementation of the abstract factory and
then use the generic interfaces to create the
concrete objects that are part of the theme
• The client does not know (nor care) about which
concrete objects it gets from each of these internal
factories since it uses only the generic interfaces of
their products
18
Abstract Factory Pattern
19
Abstract Factory Pattern Example
22
Abstract Factory Pattern Example
23
MVC Pattern
Facade Pattern
Facade Pattern
26