Top Banner
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design
23

Creational Design Patterns

Jan 31, 2016

Download

Documents

kris_ty

Creational Design Patterns. CSC 335: Object-Oriented Programming and Design. Outline. Three Creational Design Patterns Singleton Factory Abstract Factory Prototype. To use new or to not use new? That is the question. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Creational  Design Patterns

1

Creational Design Patterns

CSC 335: Object-Oriented Programming and Design

Page 2: Creational  Design Patterns

2

Outline

Three Creational Design Patterns Singleton Factory Abstract Factory Prototype

Page 3: Creational  Design Patterns

3

To use new or to not use new? That is the question.

Since most object-oriented languages provide object instantiation with new and initialization with constructors

There may be a tendency to simply use these facilities directly without forethought to future consequences

The overuse of this functionality often introduces inflexibility in the system

Page 4: Creational  Design Patterns

4

Creational Patterns

Creational patterns describe object-creation mechanisms that enable greater levels of reuse in evolving systems: Builder, Singleton, Prototype

The most widely used is Factory This pattern calls for the use of a specialized object

solely to create other objects

Page 5: Creational  Design Patterns

5

Recurring Problem• Some classes have only one instance. For example,

there may be many printers in a system, but there should be only one printer spooler

• How do we ensure that a class has only one instance and that instance is easily accessible?

Solution• Have constructor return the same instance when

called multiple times• Takes responsibility of managing that instance away

from the programmer• It is simply not possible to construct more instances

OO Design PatternSingleton

Page 6: Creational  Design Patterns

6

UML General form as UML

(From http://cvs.m17n.org/~akr/mj/design-pattern/en/design-pattern.html)

Page 7: Creational  Design Patterns

7

Java Code General Form

Page 8: Creational  Design Patterns

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 a constructor (in this case, the constructor would be a private method).

Page 9: Creational  Design Patterns

9

Implementing Singleton in Java

Make constructor(s) private so that they can not be called from outside.

Declare a single static private instance of the class.

Write a public getInstance() or similar method that allows access to the single instance.

Page 10: Creational  Design Patterns

10Patterns 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() { … }}

Page 11: Creational  Design Patterns

11Patterns I P-11

An Alternative Approachclass PhoneState {

private static PhoneState pS;

public static PhoneState getInstance() {

if (pS == null) { pS = new PhoneState(); }

return pS;

}

private PhoneState() {}

public int getNumPeople() {

}

}

Page 12: Creational  Design Patterns

12

OO Design PatternFactory Method

Name: Factory MethodProblem: A Client needs an object and it doesn't

know which of several objects to instantiateSolution: Let an object instantiate the correct

object from several choices. The return type is an abstract class or an interface type.

Page 13: Creational  Design Patterns

13

Characteristics

A method returns an objectThe return type is an abstract class or interfaceThe interface is implemented by two or more

classes or the class is extended by two or more classes

Page 14: Creational  Design Patterns

14

General Formhttp://www.dofactory.com/Patterns/PatternFactory.aspx

Page 15: Creational  Design Patterns

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 of type

Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object. •may call the factory method to create a Product object. •ConcreteCreator  (Report, Resume) •overrides the factory method to return an instance of a

ConcreteProduct.

Page 16: Creational  Design Patterns

16

Example from Java

Border is an interfaceAbstractBorder is an abstract classBorderFactory has a series of static methods

returning different types that implement BorderThis hides the implementation details of the

subclassesThe factory methods directly call the constructors

of the subclasses of AbstractBorder

Page 17: Creational  Design Patterns

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);

Page 18: Creational  Design Patterns

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);

Page 19: Creational  Design Patterns

19

Lots of Subclasses

javax.swing.border.AbstractBorder java.lang.Object javax.swing.border.AbstractBorder

All Implemented Interfaces: Serializable, Border

Direct Known Subclasses: BasicBorders.ButtonBorder, BasicBorders.FieldBorder,

BasicBorders.MarginBorder, BasicBorders.MenuBarBorder, BevelBorder, CompoundBorder, EmptyBorder, EtchedBorder, LineBorder, MetalBorders.ButtonBorder, MetalBorders.Flush3DBorder, MetalBorders.InternalFrameBorder, MetalBorders.MenuBarBorder, MetalBorders.MenuItemBorder, MetalBorders.OptionDialogBorder, MetalBorders.PaletteBorder, MetalBorders.PopupMenuBorder, MetalBorders.ScrollPaneBorder, MetalBorders.TableHeaderBorder, MetalBorders.ToolBarBorder, TitledBorder

Page 20: Creational  Design Patterns

20

Iterators?

The iterator methods isolate the client from knowing 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>();

Page 21: Creational  Design Patterns

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 €

Page 22: Creational  Design Patterns

22

What Happened?

getCurrencyInstance returns an instance of DecimalFormat where methods like setCurrency help 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 in configuration files or the jre or the OS

Page 23: Creational  Design Patterns

23

Behind the scenes

Client: main methodFactory Method: getCurrencyInstance Product: a properly configured instance of DecimalFormat

This is another example of Factory in use