1
Creational
Design Patterns
CSC 335: Object-OrientedProgramming and Design
2
Outline
Three Creational Design Patterns
Singleton
Factory
Abstract Factory
Prototype
3
To use new or to not usenew? That is the question.
Since most object-oriented languages provideobject instantiation with new and initialization withconstructors
There may be a tendency to simply use thesefacilities directly without forethought to futureconsequences
The overuse of this functionality often introducesinflexibility in the system
4
Creational Patterns
Creational patterns describe object-creationmechanisms that enable greater levels of reuse inevolving systems: Builder, Singleton, Prototype
The most widely used is Factory
This pattern calls for the use of a specialized objectsolely to create other objects
5
Recurring Problem
Some classes have only one instance. For example,there may be many printers in a system, but thereshould be only one printer spooler
How do we ensure that a class has only one instanceand that instance is easily accessible?
Solution
Have constructor return the same instance whencalled multiple times
Takes responsibility of managing that instance awayfrom the programmer
It is simply not possible to construct more instances
OO Design Pattern
Singleton
6
singleton
UML General form as UML
(From http://cvs.m17n.org/~akr/mj/design-pattern/en/design-pattern.html)
7
Java Code General Form
// NOTE: This is not thread safe!
public class Singleton {
  private static Singleton uniqueInstance;
  // other useful instance variables here
 
  private Singleton() {}
 
  public static Singleton getInstance() {
    if (uniqueInstance == null) {
      uniqueInstance new Singleton();
    }
    return uniqueInstance;
  }
 
  // other useful methods here
}
8
Participant
Singleton
Defines a constructor that returns the (single)instance of this class. Store this instance in the class(uniqueInstance).
Defines operations (SingletonOperation()) and data(getSingletonData()) for this instance.
Optionally, may also define a static method(Instance()) to return the instance, instead of aconstructor (in this case, the constructor would be aprivate method).
9
Implementing Singleton in Java
Make constructor(s) private so that they can not becalled from outside.
Declare a single static private instance of the class.
Write a public getInstance() or similar method thatallows access to the single instance.
10
Patterns I
P-10
Use Example: A PhoneState
class PhoneState {
  private static PhoneState pS = new PhoneState();
  public static PhoneState getInstance() {
    return pS;
  }
 
  private PhoneState() {}
 
  public int getNumPeople() {
    …
  }
}
11
Patterns I
P-11
An Alternative Approach
class PhoneState {
  private static PhoneState pS;
  public static PhoneState getInstance() {
    if (pS == null) { pS = new PhoneState(); }
    return pS;
  }
 
  private PhoneState() {}
  public int getNumPeople() {
  }
}
12
OO Design PatternFactory Method
Name: Factory  Method
Problem: A Client needs an object and it doesn'tknow which of several objects to instantiate
Solution: Let an object instantiate the correctobject from several choices. The return type is anabstract class or an interface type.
13
Characteristics
A method returns an object
The return type is an abstract class or interface
The interface is implemented by two or moreclasses or the class is extended by two or moreclasses
14
General Formhttp://www.dofactory.com/Patterns/PatternFactory.aspx
15
Product  (Page)
defines the interface of objects the factory method creates
ConcreteProduct 
implements the Product interface
Creator  
declares the factory method, which returns an object oftype Product. Creator may also define a defaultimplementation of the factory method that returns a defaultConcreteProduct object.
may call the factory method to create a Product object.
ConcreteCreator  (Report, Resume)
overrides the factory method to return an instance of aConcreteProduct.
16
Example from Java
Border is an interface
AbstractBorder is an abstract class
BorderFactory has a series of static methodsreturning different types that implement Border
This hides the implementation details of thesubclasses
The factory methods directly call the constructorsof the subclasses of AbstractBorder
17
One type
setSize(250, 100);
JPanel toBeBordered = new JPanel();
Border border =
   BorderFactory.createMatteBorder(2, 1, 5, 9, Color.RED);
toBeBordered.add(new JLabel("" + border.getClass()));
toBeBordered.setBorder(border);
getContentPane().add(toBeBordered, BorderLayout.CENTER);
18
Another type
 setSize(250, 100);
 JPanel toBeBordered = new JPanel();
 Border border = BorderFactory.createEtchedBorder();
 toBeBordered.add(new JLabel("" + border.getClass()));
 toBeBordered.setBorder(border);
 getContentPane().add(toBeBordered, BorderLayout.CENTER);
19
20
Iterators?
The iterator methods isolate the client fromknowing the class to instantiate
   List<String> list = new ArrayList<String>();
   Iterator<String> itr = list.iterator();
   System.out.println(itr.getClass().toString());
What type is itr?
    class java.util.AbstractList$Itr
What type is itr with this change?
   List<String> list = new LinkedList<String>();
21
Do we need new?
Objects can be returned without directly using new
 double amount = 12345.1234656789457;
 NumberFormat formatter =
           NumberFormat.getCurrencyInstance();
 System.out.println(formatter.format(amount));
Output if the computer is set to US
  $12,345.12
Change the computer setting to Germany and we get this:
  12.345,12 €
22
What Happened?
getCurrencyInstance returns an instance ofDecimalFormat where methods like setCurrencyhelp build the appropriate object
It encapsulates the creation of objects
Can be useful if the creation process is complex,for example if it depends on settings inconfiguration files or the jre or the OS
23
Behind the scenes
 
Client: main method
Factory Method: getCurrencyInstance
Product: a properly configured instance ofDecimalFormat
This is another example of Factory in use