session 07: c# design patterns design patterns composite pattern iterator pattern interfaces in the...
TRANSCRIPT
Session 07:C# Design Patterns
Design Patterns
Composite Pattern
Iterator Pattern
Interfaces in the libraries
FEN 2013-04-01 1AK - IT: Softwarekonstruktion
FEN 2013-04-01 AK - IT: Softwarekonstruktion 2
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 2013-04-01 AK - IT: Softwarekonstruktion 3
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 displayed
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 2013-04-01 AK - IT: Softwarekonstruktion 4
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
}
// More operations
}//end Circle
FEN 2013-04-01 AK - IT: Softwarekonstruktion 5
public class Picture : Shape{ List<Shape> pictList; // operations for adding, deleting etc. shapes
public void Show(){ //PRE none //POST The composite shape is drawn for(Shape s : pictList)
s.Show(); }
} public 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
Static type Shape – and Picture is a Shape itself!
FEN 2013-04-01 AK - IT: Softwarekonstruktion 6
Composite Pattern• 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 2013-04-01 AK - IT: Softwarekonstruktion 7
(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 2013-04-01 AK - IT: Softwarekonstruktion 8
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 2013-04-01 AK - IT: Softwarekonstruktion 9
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
More Examples• Organisational Structures
• demos\RecursiveDirectoryTraverse
A directory is a collection of elements which are either files or directories themselves.
FEN 2013-04-01 AK - IT: Softwarekonstruktion 10
FEN 2013-04-01 AK - IT: Softwarekonstruktion 11
Exercises
• Exercise 4 on Session07.docx.
Interfaces• An interface may be seen as a purely abstract class.
– Interface: only method signatures, no implementation! (All methods are abstract)
• An interface represents a design.• Example:
– Designing an object that can be used for iterating over a data structure.
public interface IEnumerator{ void Reset(); // reset iterator to beginning bool MoveNext(); // advance to next element object Current { get; } // retrieve current element}
FEN 2013-04-01 12AK - IT: Softwarekonstruktion
Also as generic
Example – Iterator Pattern• This piece of client code iterates over any data structure that
implements IEnumerator:
IEnumerator iter;
iter = ...; // get ref to iterator object
iter.Reset();while ( iter.MoveNext() ) MessageBox.Show( iter.Current.ToString() );
iterator
datastructure
See it work!FEN 2013-04-01 13AK - IT: Softwarekonstruktion
Different Collections• List:
– Array-based (static)– Supports access by
position– Uses extra memory– Expensive when re-
allocating
• LinkedList:– Linked list (dynamic, no
extra memory) – Doesn’t support access
by position.
FEN 2013-04-01 AK - IT: Softwarekonstruktion 14
• HashSet (Dictionary):• Array-based (static)• Supports fast access (in average)
by key – slow in worst case• Uses extra memory• Expensive when re-allocating
• SortedSet (SortedDictionary):• Search tree (dynamic, no extra
memory)• Supports fast access (logarithmic)
in average and worst case.
In .NET interfaces are used heavily.
• IComparable• ICloneable• IDisposable• IEnumerable & IEnumerator• IList• ISerializable• IDBConnection, IDBCommand, IDataReader• etc.
FEN 2013-04-01 15AK - IT: Softwarekonstruktion
Typical Design in APIs
• Specification in the interface.• Implementation in the concrete
classes.• Operations with common
implementation are implemented in the abstract class (no code duplication).
• Operation specific for the different concrete classes are left abstract in the abstract class.
FEN 2013-04-01 16AK - IT: Softwarekonstruktion
Example: Sorting
• Goal: – To write a generic Sort() method as the one
found in System.Array
FEN 2013-04-01 17AK - IT: Softwarekonstruktion
Step 1: Define the interface
• Sorting requires a way of comparison of objects:
• returns < 0 if this object < obj parameter
• returns == 0 if this object = obj parameter• returns > 0 if this object > obj parameter• returns < 0 if this object < obj parameter
public interface IComparable<T>{ int CompareTo(T obj);}
FEN 2013-04-01 18AK - IT: Softwarekonstruktion
Step 2: Classes must implement the interface
• Objects That are to be sorted must implement IComparable><>
• Example:– sort Student objects on id
public class Student : Icomparable<Student>{ private int m_ID; . . .
int IComparable.CompareTo(Student other) { return this.m_ID – other.m_ID; }}
interface
Student
type
FEN 2013-04-01 19AK - IT: Softwarekonstruktion
Step 3: Clients program towards the interface
• Sort assumes that the elements in the array a implement IComparable:
public class Array{
public static void Sort(Array a) { IComparable icobj;
for (int i = 0; i < a.Length-1; i++) { for (int j = i+1; j < a.Length; j++) { icobj = (IComparable) a.GetValue(i); if (icobj.CompareTo(a.GetValue(j)) > 0) swap(a, i, j); }//for }//for }
}
FEN 2013-04-01 20AK - IT: Softwarekonstruktion
Step 4: test!• Example: sort an array of Student objects
View CodeFEN 2013-04-01 21AK - IT: Softwarekonstruktion
FEN 2013-04-01 AK - IT: Softwarekonstruktion 22
Exercises
• Exercise 5 on Session07.docx.