Design Patterns
Examples of smart use of inheritance and polymorphism:
Composite Pattern
State Pattern
FEN 2014 UCN Teknologi/act2learn 1
UCN Teknologi/act2learn 2
(OO) Design Patterns• The concept of patterns originates from architecture (Christopher
Alexander, 1977):
“Each pattern describes a problem which occurs over and over again in our environment, and then
describes the core of the solution to that problem, in such a way that you can use this solution a million
times over, without ever doing it the same way twice”
(Christopher Alexander e. a.: “A Pattern Language”. Oxford University Press, New York, 1977.)
FEN 2014
UCN Teknologi/act2learn 3
(OO) Design Patterns
• A well known and widely accepted concept in software engineering
• Developed in the early 1990s and published by Gamma e.a. (“Gang of Four”, GoF) in 1995:
“(…) design patterns (…) are descriptions of communicating objects and classes that are
customized to solve a general design problem in a particular context.”
(Erich Gamma e.a.:”Design Patterns. Elements of Reusable Object-Oriented Software”. Addison-Wesley. 1995.)
FEN 2014
UCN Teknologi/act2learn 4
The benefits of patterns
• A pattern captures a proven good design:– A pattern is based on experience– A pattern is discovered – not invented
• It introduces a new (and higher) level of abstraction, which makes it easier:– to talk and reason about design on a higher level– to document and communicate design
• One doesn’t have to reinvent solutions over and over again• Patterns facilitate reuse not only of code fragments, but of
ideas.
FEN 2014
UCN Teknologi/act2learn 5
Patterns as a learning tool
• It is often said that good skills in software construction require experience and talent
• …and neither can be taught or learned at school• Patterns capture experience (and talent) in a way that
is communicable and comprehensible• …and hence experience can be taught (and learned)• So one should put a lot of effort in studying patterns
FEN 2014
UCN Teknologi/act2learn 6
Example: Composite-pattern
1
Circle Rectangle Picture
Shape
0..*0..*
Position
1
Composite: Graphical editor, Word processor, Inventories etc..
(What will a Show()-method look like on Shape, Circle, Picture etc.)
FEN 2014
UCN Teknologi/act2learn 7
public abstract class Shape {private int id;private String color;private int xpos;private int ypos;
public void MoveTo(Position newPos){ // PRE none // POST pos'=newPos }
public abstract void Show();// PRE none
// POST the shape is drawn
public abstract void Hide(); // PRE none // POST the shape is hidden public abstract float Area();
// PRE none// POST Computes the area with 4 digits.
}//end Shape
FEN 2014
UCN Teknologi/act2learn 8
public class Circle: Shape{
private int r; //radius
public void Show(){
//PRE none
//POST the circle is drawn
//Must be implemented using appropriate
//graphical routines
}
public void Hide(){
//PRE none
//POST the circle is hidden
//Must be implemented using appropriate
//graphical routines
}
public override float Area()
{
return (float)(r*r);
}
}//end CircleFEN 2014
UCN Teknologi/act2learn 9
public class Picture : Shape{ List<Shape> pictList; // operationer til at tilføje og slette figurer mv. public void Show(){ //PRE none //POST The composite shape is drawn foreach(Shape s in pictList)
s.show(); }
} public override float Area() { float result=0; for(int i=0;i<pictList.Count;i++) { result= result+pictList[i].Area(); } return result;
}//end Picture
Dynamic type definesshow()
Static type
FEN 2014
Composite Pattern
FEN 2014 10UCN Teknologi/act2learn
• Can be used to model general tree structures
General Tree
FEN 2014 11UCN Teknologi/act2learn
AbstractTreeElement
Leaf Tree
0..*
More Examples/Exercises
• Organisational Structures (example)• Project Management (exercise)
• Composite Pattern can be found in the .NET libraries: demos\RecursiveDirectoryTraverse
UCN Teknologi/act2learn 12FEN 2014
State Pattern
Models state machines
(DFAs: Deterministic Finite Automata).
FEN 2014 UCN Teknologi/act2learn 13
Example: Controlling a printer(from: http://www.go4expert.com/forums/showthread.php?t=5127)
FEN 2014 UCN Teknologi/act2learn 14
To implement this, we need a set of events E, and a set of states S, and a transition function t:
t(E, S) -> S
that gives the next state.
Implementations of DFAs• Choose an appropriate data structure to represent states:
– A List or– A Dictionary– A …?
FEN 2014 UCN Teknologi/act2learn 15
event
state
2
states
n-1i0
s1
Find a way to implement the transition function:
– A matrix perhaps?
Difficult to maintain.
OO Implementation
• State is an object• State Pattern can be applied:
– abstract class State specifies one or more abstract methods:• transition(-) – returns state corresponding to next event• action(-) – if any processing is to be done when a transition
occurs (code generation, event handling etc.)• each concrete state inherits from State and implements the
abstract methods
• The controller loop uses references having the abstract class State as static type.
• Polymorphism and dynamic binding handles the rest!
FEN 2014 UCN Teknologi/act2learn 16
Class Diagram
FEN 2014 UCN Teknologi/act2learn 17
Note how the design reflects the structure of the state machine
FEN 2014 UCN Teknologi/act2learn 18
View source
Exercise: Add a new event: “Paper Jam”, which can occur in the state “Printing” and brings the printer in an error state where it remains stopped.
State Pattern
FEN 2014 UCN Teknologi/act2learn 19
The Classes of the Pattern
• Context: Defines the objects that we want maintain state information about (for instance DialogBox) . This class has a reference (static type: ContextState – the abstract super class) to some concrete state (that is an object of one of the sub classes – dynamic type).
• ContextState: The abstract super class defining a common interface to all the concrete states.
• ConcreteState1,...: The sub classes to ContextState. One sub class to each state in the DFA. The key to the design is in the processEvent-method, which takes an event as input and returns the next state. The method is abstract in ContextState and implemented (differently) in the subclasses.
FEN 2014 UCN Teknologi/act2learn 20