Design Patterns and Refactoring
Creational Patterns: Motivation
Oliver Haase
HTWG Konstanz
A Simple, Motivating Example . . .
Assume an oversimplified document manager that can create, open, and close a LaTeX document:
p u b l i c c l a s s DocManager { p r i v a t e L a t e x D o c doc ;
p u b l i c v o i d newDoc ( ) { doc = new L a t e x D o c ( ) ; }
p u b l i c v o i d openDoc ( ) { doc . open ( ) ;
}
p u b l i c v o i d c l o s e D o c ( ) { doc . c l o s e ( ) ;
} }
But. . .
. . . What about the first principle of reusable software design?
⇓
OK, makeLatexDocan implementation of an interface:
interface Document open(): void close(): void
Lat exDoc open(): void close(): void
But. . .
. . . What about the first principle of reusable software design?
⇓
OK, makeLatexDocan implementation of an interface:
interface Document open(): void close(): void
Lat exDoc open(): void close(): void
But. . .
. . . What about the first principle of reusable software design?
⇓
OK, makeLatexDocan implementation of an interface:
interface Document open(): void close(): void
Lat exDoc open(): void close(): void
Then . . .
Make docan instance ofDocument, rather thanLatexDoc:
p u b l i c c l a s s DocManager { p r i v a t e Document doc ;
p u b l i c v o i d newDoc ( ) { doc = new L a t e x D o c ( ) ; }
p u b l i c v o i d openDoc ( ) { doc . open ( ) ;
}
p u b l i c v o i d c l o s e D o c ( ) { doc . c l o s e ( ) ;
} }
Dependency Situation
Now, DocManagerhas become dependent on both Documentand LatexDoc:
interface Document open(): void close(): void DocManager
Lat exDoc open(): void close(): void
So What?
What’s wrong with this creational dependeny?
DocManagercannot be used for other document types, e.g. plain text documents, even though its functionality is applicable to other document types as well;
Difficult to use document mock-up for testing;
In a framework, DocManagerwould not even know – and care about – what document type to create.
⇓
Creational patterns are all about removing this creational dependency.