Design Patterns in C#
Design Patterns in C#
Mathias Bartoll
Nori Ahari
Oliver C. Moldez
Department of Computer Science
Mlardalen University
Vsters, Sweden
mathias@mathiasbartoll.com
nori@ahari.info
oca99001@student.mdh.se
4 Juni, 2004
Abstract
The idea behind design patterns is to save good object oriented design
solutions and reuse them to solve similar problems. In The early 1990:s
Erich Gamma et al [1] described 23 design patterns, six of which will be
described here.
The new object oriented language C#, presented by Microsoft is strongly
influenced by Java and C++. Still some new and interesting features are
introduced that simplify object oriented design. As it is shown in this work
interfaces can be used to implement patterns such as Adapter and Strategy,
and Events come in handy when the Observer pattern is to be used. However
C# is intended to work together with the .NET platform and is therefore
tightly coupled with some .NET specific issues.
1 Introduction
Object oriented programming has been the dominating style in software development for quite a few years. The intuitive way in which object oriented languages
allow us to divide our code into objects and classes is what makes this style of
programming attractive. Another aim of object oriented program design is to make
code more reusable. After all an object, say for example a chair, will always be
a chair and if we write a chair class for a program, it is likely that we can reuse
that class in another context. It has however been shown that designing reusable
object oriented software is not always that easy. A good software design should,
not only solve existing problems, but also concern future problems. It should make
the program flexible, easy to maintain and to update. Design patterns help us address these issues. The idea is quite simple; we want to document and save design
solutions that have been used and worked for reoccurring problems, in order to use
them again in similar situations. Erich Gamma et. al describe 23 different design
patterns in their book [1]. This book is one of the first publications in the area.
The aim of this work is to take a closer look at how some of the known design
patterns can be implemented in C#, and to investigate whether the new features of
the language in fact do make it easier to design object oriented software. This paper
should not be seen as an introduction to C#. We will briefly go through some of
the features of the language that are relevant to implementing most design patterns,
whereas some other details are omitted. For a more extensive overview of C# the
reader is referred to some of the references at the end of this work.
Since C# is closely related to the .NET platform we will start by a short introduction to the .NET framework in the next chapter. Chapter 3 covers some features
in C#, in chapter 4 we describe six of the design patterns presented by Gamma et.
al [1] and look at how they can be implemented in C#. And finally the work will
be wrapped up by some discussions and conclusions.
2 .NET Framework
2.1 Introduction
The .NET platform is a new development framework providing a new Application
Programming Interface (API), new functionality and new tools for writing Windows and Web applications. But it is not only a development environment, it is also
an entire suite of servers and services, as shown in figure 1 [7], that work together
to deliver solutions to solve todays business problems. One of the main ideas with
.NET is to make the connectivity and interoperability between businesses easier.
In this section we will briefly focus on the main aspects in .NET Framework that
relates to the C# language. These two technologies are very closely intertwined.
The basic idea of .NET Framework is to have several languages use the same underlying architecture, which should have a natural relationship with the various
forms of the Windows operating system. Most of Microsofts next generation of
These sections are shown in figure 3 illustrated by Thai T. et. al [7]. The CLR
header stores information to indicate that the PE file is a .NET executable and the
CLR data section contains metadata and Microsoft Intermediate Language (MSIL,
or IL for short) code. Every common language runtimecompliant development
lays its support for defining and working with classes. Classes define new types,
allowing you to extend the language to better model the problem you are trying to
solve. C# contains keywords for declaring new classes with methods and properties, and also for implementing encapsulation, inheritance and polymorphism, the
three pillars of object-oriented programming. Some other key features of this language include interfaces, delegates, namespaces, indexers, events and attributes.
No header or Interface Definition Language (IDL) files are needed.
The .NET software development kit defines a "Common Language Subset"
(CLS), which ensures seamless interoperability between CLS-compliant languages
and class libraries. For C# developers, this means that even though C# is a new
language, it has complete access to the same rich class libraries that are used by
seasoned tools such as Visual Basic and Visual C++. C# itself does not include a
class library.
There are several advantages of sharing libraries across languages. It reduces
learning time when moving from one .NET-supported language to another. It provides a larger body of samples and documentation, because these do not need to be
language specific. It also allows better communication between programmers who
work in different .NET-supported languages.
This part covers some of the key features that the C# language provides for
the developer. You will see that some of these features will be very useful when
implementing design patterns.
The student class defined here has two constructors. A constructor does not have
a return value. Notice also that each method can be overloaded with different type
or number of arguments.
class student
{
public student(string stName)
{
name = stName;
}
public student(string stName, string gr)
{
name = stName;
grade = gr;
}
public void SetGrade(string gr)
{
grade = gr;
}
public string GetGrade()
{
return grade;
}
private string name;
private string grade;
}
Each C# application must contain at least one class that has a main method. It is
also required that main is defined as public and static. For example:
class studentApp
{
public static void main()
{
student st = new student("Nori");
st.SetGrade("A");
}
}
The main method works as the entry point for the application, however you can
have several classes containing a main method in C#. In that cases you need to
specify at compile time which classs main method should be used as the applications entry point. This can be done by using the compilers main switch like the
following:
csc multipleMain.cs / main:studentApp
Here the csc is the C# compiler, multipleMain is the file we are compiling and
studentApp is the name of the class that contains the main method we want to
use as the entry point.
3.2.2 Inheritance
Inheritance in C# works in the same fashion as with other object oriented languages. The inherited class can be viewed and treated as the base class but not the
other way around. The syntax for inheriting a class from another is as follows:
class derivedClass : baseClass
Where derivedClass is the name of the new class, and baseClass is the name
of the base class. C# does not allow multiple inheritance, however the concept of
interfaces is introduced to be used instead. Interfaces are described later in chapter
3.5.
3.2.3 Ref and Out Method Arguments
Recognising the fact that pointers are one of the biggest source of bugs when developing software, the concept of pointers, as known in C and C++, does not exist
in C#. It is however still possible to pass reference variables as method arguments
by using the keywords ref and out.
Consider the example of a colour class that contains three member variables
of type integer, namely red, green, and blue. These three variables determine the
value of the colour class based on the RGB standard [6]. Using reference variables
we can retrieve all three values through a single method call. The code would look
something like this:
class colour
{
private int red;
private int green;
private int blue;
public void GetColors(ref int red, ref int green, ref int blue)
{
red = this.red;
green = this.green;
blue = this.blue;
}
}
The
...
int
int
int
to each other because both have been introduced to make client access to classs
members more intuitive. Also the syntax of defining properties and indexers are
very similar. That is why both of theses concepts will be covered together in this
chapter. We will start by looking at properties, then see how arrays work in C# and
finally how indexers can be used to treat objects as arrays.
3.3.1 Properties
It is common object oriented practice to declare some of the members of a class as
private and allow access to these members only through public accessor methods,
sometimes called getters and setters. This approach can be useful if you for
example want to perform some verification on the input from the client before
you let the value of your member variable change. Consider a class containing a
streetAddress member and a zipCode member. In this case it would be a good idea
to verify that the zip code provided by the client is consistent with the classes street
address [6]. This could be done in the following fashion:
class address
{
protected string streetAddress;
protected string zipCode;
public string getZipCode()
{
return (zipCode);
}
public void setZipCode(string zc)
{
// Validate the zip code against a database
zipCode = zc;
}
}
Code at the client side uses the setZipCode method to pass a new zip code to the
class. C# properties provide the same functionality but make the code at the client
side more elegant by letting the private members be accessed as though they were
public, but still allowing the client to perform the necessary validation. Here is the
example above rewritten using properties:
class address
{
protected string streetAddress;
protected string zipCode;
3.3.3 Indexers
Indexers are a mechanism to let you treat any object as though it was an array. One
example of where this would make sense is a windows listbox class (See MSDN
for more information) that should provide the clients by some methods that enables
them to insert strings into the listbox, or access and modify existing strings. The
Microsoft Foundation Classes (MFC) provides a class called CListBox that lets us
operate on a listbox through member functions such as AddString and InsertString.
In its simplest form the listbox could be viewed as an array of strings. It would be
elegant if we could operate directly onto its string members in the following way:
listboxClass lb = new listboxClass();
lb[0] = "some data";
lb[1] = "some other data";
This can be done through C# indexers. The syntax of defining indexers is quite
similar to defining properties. The difference is that the indexer takes an index
argument and the this keyword is used as the name of the indexer to imply that
the class itself is being used as an array [6]. In the following example we use a
.NET built in type called ArrayList, which is used to store a collection of objects,
to illustrate how we can define our own listbox class. Through the use of indexers
the class can be treated as an array:
using System;
using System.Collections;
class MyListBox
{
protected ArrayList data = new ArrayList();
public object this [int idx]
{
get
{
return(data[idx]);
}
set
{
// If there already exists some data at the
// given index, replace it with the new data
if (idx > -1 && idx < data.Count)
{
data[idx ] = value;
}
// Else add the new data to the ArrayList
3.4 Attributes
Attributes in C# is a technique to add metadata to your classes. Metadata is declarative information about elements of source code, such as classes, members, method
etc. The information provided by the attribute is stored in the metadata of the element and can be retrieved at runtime by a technique called reflection. The use of
attributes allows you to change the behaviour of an object at runtime, provide information about an object or objects in your application, and to mediate information
to other designers. Attributes can even by useful when debugging.
Attributes were introduced by Microsoft to allow the developer to add declarative information to the source code and to get rid of the DLL hell [8]. Instead
having two files for a component, one that contains the application and another the
application information, attributes add the metadata along with the application assembly. With DLL:s you need both files for the component to function and if one
is lost you could not use the component.
An attribute is a class that you can add to different programming elements,
such as assemblies, objects, struct, enums, constructor, methods, return values,
and delegates. All attributes are derived from the System.Attribute class. There
are two kinds of attributes, intrinsic and custom. Intrinsic attributes are a part of
the CLR and they are the most common used attributes. Custom attributes are
attributes created by developer. When applying an attribute, it must be placed
directly after the using statement and before the class declaration. The formal
syntax of an attribute is:
using System;
Reflection is used to access the attributes information at runtime as mentioned earlier. The MemberInfo class is used for retrieving information stored by attributes
in the metadata. MemberInfo class is found in System.Reflection namespace.
System.Reflection.MemberInfo[ ] attributeArray;
attributeArray = typeof(myClass).GetCustomsAttributes( );
After getting the array you can iterate through the array to get the information
stored in the attributes.
foreach(Attribute atr in attributeArray)
{
if (atr is myAttribute)
{
myAttribute myA = (myAttribute)atr;
Console.WriteLine("Web page = {0} , class {1} = ",
myA.Url, myA.Subject);
}
}
3.5 Interfaces
One feature not supported by the C# programming language is multiple inheritance. As an example of where multiple inheritances is useful consider the following:
Lets say that you are programming a university application in which you use
an employee class to represent a person employed by the university. A researcher
is a subclass of employee with tasks such as doing experiments and writing papers.
Researchers also sometimes teach courses. There are also other people teaching
courses that are not researchers. Multiple inheritance would have allowed you to
create a new class called something like Teacher and let the researcher class, along
with other employee subclasses who teach courses, inherit both from the employee
and from the Teacher classes. In this case a researcher is an employee, which also
should display the characteristic behaviours of a teacher. C# introduces interfaces
as a built in part of the language to represent behaviours as opposed to classes that
represent objects [6].
An interface is basically a contract between a class and a client that guaranties
that the class implements the methods specified in the interface. In other words,
interfaces contain the public signature of methods, events and properties but it is up
to the class, which is said to implement the interface, to provide the implementation
of these methods. The implementing class inherits from an interface in the same
way as from a base class. An instance of this class can then be casted into the
interface and access its methods. In this way interfaces can be used to reach the
same objectives as with multiple inheritance.
As an example we can crate an interface called ITeach and let the resarcher
class (described above), which also inherits from an employee base class, implement it.
interface ITeach
{
string SetGrade(string studentId);
}
class employee
{
protected int Salary;
public int salary
{
get { return this.Salary; }
set { this.Salary = value; }
}
protected string Emp_ID;
public string emp_ID
{
get { return this.Emp_ID; }
set { this.Emp_ID = value; }
}
}
class reseracher: employee, ITeach
{
public researcher(string id, int sal)
{
emp_ID = id;
salary = sal;
}
public string SetGrade(string studentId)
{
if (studentId == "Martin")
return("A")
else
return("D")
}
}
As mentioned above an instance of the researcher class can be casted into the interface(s) it implements. This means that we can use the is and as operators to see
whether or not a class implements a certain interface or not. The is operator can
be used to see whether the runtime type of an object is the same as another, and
returns a Boolean value. The keyword as is used to cast an object into another
type and returns null if the cast fails. The following example illustrates this:
class MyApp
{
static void main()
{
researcher R = new researcher("Martin", 20000);
if(R is ITeach)
{
ITeach T = (ITeach)R;
T.SetGrade("Nori");
}
// Alternatively
ITeach T = R as ITeach;
if(T != null)
T.SetGrade("Nori");
}
}
In this particular case however it is not necessary to cast R into ITeach. Note how
the researcher class declares the SetGrade method:
public string SetGrade(string studentId)
This means that SetGrade exists in the public namespace of the researcher class
and can be invokeddirectly on an instance of researcher:
R.SetGrade("Nori");
If researcher however had implemented the SetGrade function in the following
way the cast would have been necessary:
string ITeach.SetGrade(string studentId)
}
catch(System.Exception e) {
// Code to execute if an exception happened.
}
The Exception is handled in the nearest catch block, but if theyre no catch block
to handle the exception the CLR unwinds the stack until it find an appropriate exception handler (catch block). If CLR returns back to main() and still no exception
handler is found then the application is terminated.
Those who are familiar with C++ recognise this error handling technique, but
there are some new features provided by C#. You can declare a finally block to
your error handling code. The finally block provides a way to guarantee that a
peace of code is always executed whether an Exception is thrown or not.
try {
// Code to monitor for exceptions
}
catch (System.Exception e) {
// Code to handle the exception
}
finally {
// Code that always is executed whether
// an exception is thrown or not.
}
Some other new features are as mentioned earlier that all Exceptions derive from
the System.Exception class while in C++ any type can be used as an Exception.
All System-level Exceptions are well defined in Exceptions classes. In C# you
can create and throw your own Exceptions as long as they derive from the System.Exception class. All Exceptions that are caught in the catch block can be
thrown again.
catch (System.Exception cought) {
throw caught;
}
3.7.1 Delegates
In chapter 3.5 we saw how interfaces specify a contract between a caller and an
implementer. Delegates are similar to interfaces but rather than specifying an entire
interface, a delegate merely specifies the form of a single method. Also, interfaces
are created at compile time, whereas delegates are created at runtime.
As Liberty [5] states, in the programming language C#, delegates are first-class
objects, fully supported by the language. Using a delegate allows the programmer
to encapsulate a reference to a method inside a delegate object. You can encapsulate any matching method in that delegate without having to know at compile time
which method that will be invoked. A delegate in C# is similar to a function pointer
in C or C++. But unlike function pointers, delegates are object-oriented, type-safe
and secure managed objects. This means that the runtime guarantees that a delegate
points to a valid method and that you dont get errors like invalid address or that
a delegate corrupting the memory of other objects. Furthermore, delegates in C#
can call more than one function; if two delegates are added together, a delegate that
calls both delegates is the result. Because of their more dynamic nature, delegates
are useful when the user may want to change the behaviour of the application. For
example, a collection class implements sorting, it might want to support different
sort orders. The sorting could be controlled based on a delegate that defines the
comparison function.
There are three steps in defining and using delegates: declaration, instantiation,
and invocation. Delegates are declared using the keyword delegate, followed by a
return type, the signature and the parameters. In the following example we define
a class with a callback function using a delegate.
using System;
class TestDelegate
{
// 1. Define a callback prototype - Declaration
delegate void MsgHandler(string strMsg);
// 2. Define callback method
void OnMsg(string strMsg)
{
Console.WriteLine(strMsg);
}
public static void Main( )
{
TestDelegate t = new TestDelegate( );
// 3. Wire up our callback method - Instantiation
MsgHandler msgDelegate = new MsgHandler (t.OnMsg);
4 Design Patterns
4.1 Introduction
When working on a particular problem, it is unusual to tackle it by inventing a new
solution that is completely dissimilar from the existing ones. One often recalls a
similar problem and reuses the essence of its solution to solve the new problem.
This kind of thinking in problem solving is common to many different domains,
such as software engineering.
Design patterns are important building blocks for designing and modelling applications on all platforms. Design patterns help us understand, discuss and reuse
applications on a specific platform. The most commonly stated reasons for studying patterns are; reuse of solutions and establishment of common terminology. By
reusing already established designs, the developer gets a head start on the problem
and avoids common mistakes. The benefit of learning from the experience of others results in that he does not have to reinvent solutions for commonly recurring
problems. The other reason for using patterns is that common terminology brings
a common base of vocabulary and viewpoint of the problem for the developers. It
provides a common point of reference during the analysis and design phase of a
project.
The design patterns are divided into three types: creational, structural, and behavioural. Well be looking at two patterns from each category and present these
in a C# point of view. To fully understand design patterns, knowledge of the object oriented paradigm and some familiarity with the Unified Modelling Language
(UML) is required.
else
{
spoolerInstance = new Spooler();
return spoolerInstance;
}
}
}
When the spooler is created the value of the variable instance_flag is changed.
Since the instance_flag is a static class variable there can only be one instance_flag,
thus we have ensured that a single instance of a printer spooler exists. The spooler
is created in the getSpooler method instead of the constructor. Note that the constructor is private, so any attempt to access the Spooler constructor will fail. How
does C# facilitate a global access point for the printer spooler class? By defining a
static class method. Static methods can only be called from the classes and not the
class instances.
For example if we add a static instance, queueThis(string filName), to the
Spooler class.
public class Spooler
{
private static Spooler spoolerInstance = null;
private string [] queueList;
private spooler()
{
}
public static Spooler getSpooler()
{
if(spoolerInstance != null)
return spoolerInstance;
else
{
spoolerInstance = new Spooler();
return spoolerInstance;
}
}
public static Spooler queueThis(string filename)
{
// Code to add filename to the queue
}
}
And we have, by defining the queueThis method, created a global access point to
the printer Spooler. The singleton example was from [2].
{
string _type = "mustang";
public override string type
{
get { return _type; }
}
}
class concreteNorthAmericaFactory : aeroplanFactory
{
public override aeroplane getAeroplane ()
{
return new aeroplaneProductMustangP51();
}
}
Now that we have the factory and the product we are ready to implement the classes
and build our aeroplane. But first we need a client and a main class. For our client
class we implement the testpilot class.
class testpilot
{
public void askformodel(aeroplaneFactory factory)
{
aeroplane aircraft = factory.getAeroplane();
Console.WriteLine("Planemodel {0}",aircraft.type);
}
}
class MainClass
{
static void Main (string[] args)
{
aeroplaneFactory factory = new concreteNorthAmericaFactory();
new testpilot().askformodel(factory);
}
}
Now we are going to add another factory and another type of aeroplane.
class aeroplaneProductFW190 : aeroplane
{
string _type = "Foker-Wulf 190";
public override string type
{
get { return _type; }
}
}
class concreteFokerWulfFactory :aeroplanesFactory
{
public override aeroplane getAeroplane ()
{
return new aeroplaneProductFW190();
}
}
We just need to modify the main class a little to be able to use the new factory. Note
that we do not change the client class (testpilot) the interface remains the same.
class MainClass
{
static void Main (string [] args)
{
aeroplaneFactory factory = null;
if (args.length > 0 && args[0] == "P51")
factory = new aeroplaneNorthAmericaFactory();
else if ( args.length > 0 && args[0] == "FW190")
factory = new aeroplaneFokerWulfFactory();
new testpilot().askformodel(factory);
}
}
This simple example shows how you can add a new factory to you system but you
can see it is easy to add new products as well. You just add new aeroplanes and
change in the code how to choose the new products (aeroplanes).
4.3.1 Adapter
The Adapter pattern sometimes also known as wrapper is used whenever we want
to change the interface of an object into another, desired interface. This is useful
in the following scenario: An application accepts a set of functions or a certain
interface to be implemented. The same application (or class) needs to communicate with an object that provides the functionality we are looking for but does not
support the exact interface required by the application.
Consider for example the following [1]: A graphics application uses an abstract
Shape class. Each graphical shape such as circle, triangle and polygon is a subclass
of Shape and implements its own drawing function. The drawing function for a
TextShape object however might be more difficult to implement. Lets say that we
find an off the shelf object called TextView that provides us with the functionality
we are looking for. TextView however is not compatible with the Shape class.
There are mainly two way of applying the adapter pattern to make the TextView
class work with our application: class and object [1]. Class means that we inherit
Shapes interface and TextViews implementation. Object means that we hold an
instance of TextView inside TextShape and implement Shapes interface in terms of
TextView. figure 6 and figure 7 illustrate a diagram for the two methods respectively.
Both approaches are fairly easy to implement in C#. Lets look at an example
on each approach. First looking at the Object approach, we assume that the
application demands that each shape implements a Draw method (along with any
other methods we might need). Based on our previous discussion on interfaces we
can present an interface, perhaps called IDisplay containing the methods necessary to reflect this particular behaviour. This way the functionality in the TextView
object could be used if we let TextShape inherit from TextView. We can then add
the methods we need to TextShape by letting it implement the IDisplay interface.
This is the class approach of implementing the adapter pattern and would look
something like the following in code:
interface IDisplay
{
void Draw();
}
class TextView
{
...
public DisplayText()
{
...
}
...
}
class TextShape: TextView, IDisplay
{
...
public Draw()
{
this.DisplayText();
}
...
}
Notice that in the class approach, introducing an interface is necessary since C#
does not support multiple inheritance. Which approach is more suitable to use
depends on the situation. In this case if we already have built our application
around a class hierarchy with Shape as an abstract base class, the first approach is
probably more suitable. In other situations it might be a better idea to introduce
an interface. Ultimately it is up to the developer to decide where and when to use
each approach.
4.3.2 Composite
The composite pattern is designed to deal with situations where a certain object
can either be viewed individually, or as a placeholder for a collection of objects
of the same type. Consider for example a graphics application that will let you
group a collection of simple graphic objects, such as lines and texts, into a picture.
A picture which itself is a graphic object can in turn contain other pictures. The
composite patterns allows us to treat all graphic objects, independent of whether
they are complex (pictures) or simple (lines), in an uniform fashion. This can be
achieved by introducing an abstract base class that represent both the simple and
complex type. This abstract type contains methods that are shared between the
and how the flow is controlled in a complex program. They move the focus away
from the flow of control and let the developer concentrate on the way objects are
interconnected.
4.4.1 Observer
The Observer pattern lets one part of a system know when an event takes place in
another. According to Gamma et. al [1] it is a one-to-many dependency between
objects; if one-object changes state the other dependent objects will automatically
be notified and updated.
The most obvious use of the Observer pattern is when a change of one object
requires changing of an unknown number of objects. The notifying object should
not have knowledge about who these objects are. The objects arent supposed to
be tightly coupled; the Observer pattern is an example of a decoupling pattern.
It could also be applicable if the abstraction has two aspects and you would like
to encapsulate these aspects in separate objects. This will make the objects more
reusable and allow you to change them independently.
The following class diagram from Gamma et. al [1], figure 10, shows the
relationship between the Subject and the Observer. The Subject may have one
or more Observers, and it provides an interface to attaching and detaching the
observer object at run time. The observer provides an update interface to receive
signals from the subject. The ConcreteSubject stores the subject state interested
by the observers, and it sends notification to its observers. The ConcreteObserver
maintains reference to a ConcreteSubject, and it implements an update operation.
When designing and implementing the Observer pattern in C# we take advantage
the foundation of this pattern is incorporated into the core of the .NET Framework.
The Framework Class Library (FCL) makes extensive use of the Observer pattern
throughout its structure.
With figure 10 in mind, the subject is the class declaring the event. The subject
class doesnt have to implement a given interface or to extend a base class. It just
needs to expose an event. The observer must create a specific delegate instance and
register this delegate with the subjects event. It must use a delegate instance of the
type specified by the event declaration otherwise the registration will fail. During
the creation of the delegate instance, the name of the method (instance or static)
is passed by the observer that will be notified by the subject to the delegate. Once
the delegate is bound to the method it may be registered with the subjects event
as well as it can be unregistered from the event. Subjects provide notification to
observers by invocation of the event.
The following example is from Purdy D. et. al [4] and shows how to use delegates and events in the Observer pattern. The class, Stock, declare a delegate and
an event. The instance variable askPrice fires an event when its value is set.
public class Stock
{
public delegate void AskPriceDelegate(object aPrice);
public event AskPriceDelegate AskPriceChanged;
object askPrice;
public object AskPrice {
set
{
askPrice = value;
AskPriceChanged(askPrice);
}
}
}
The StockDisplay class represents the user interface in the application.
public class StockDisplay
{
public void AskPriceChanged(object aPrice) {
Console.Write("The new ask price is:" + aPrice + "\r\n");
}
}
The main class first creates a new display and a stock instance. Then it creates a
new delegate and binds it to the observers AskPriceChanged method. After that,
the delegate is added to the event. Now when we use the set property of the stock
class an event is fired every time. The delegate captures the event and executes
the AskPriceChanged method, which in this case outputs the price in the console
window. Before we quit the application, we remove the delegate from the event.
public class MainClass
{
public static void Main()
{
StockDisplay stockDisplay = new StockDisplay();
Stock stock = new Stock();
Stock.AskPriceDelegate aDelegate = new
Stock.AskPriceDelegate(stockDisplay.AskPriceChanged);
stock.AskPriceChanged += aDelegate;
for(int looper = 0; looper < 100; looper++)
stock.AskPrice = looper;
stock.AskPriceChanged -= aDelegate;
}
}
4.4.2 Strategy
The Strategy pattern defines a family of algorithms, encapsulates the related algorithms and makes them interchangeable. This allows the selection of algorithm to
vary independently from clients that use it and allows it to vary over time [4].
An application that requires a specific service or function and that has several
ways of executing that function is a candidate for the Strategy pattern. The choice
of proper algorithms is based upon user selection or computational efficiency. The
client program could tell a driver module (context) which of these strategies to
use and then tell it to carry out the operation. There are a number of cases in
applications where we would like to do the same thing in several different ways
like; compress files using different algorithms or save files in different formats.
The construction behind the Strategy pattern is to encapsulate the number of
strategies in a single module and provide an uncomplicated interface to allow the
clients to choose between these strategies. If you have several different behaviours
that you want an object to perform, it is much simpler to keep track of them if each
behaviour is a separate class, instead of the most common approach of putting
them in one method. This is illustrated in figure 11 from Gamma et. al [1]. By
doing this you can easily add, remove, or change the different behaviours, since
each one is its own class. Each such behaviour or algorithm encapsulated into its
own class is called a Strategy. The strategies do not need to be members of the
same class hierarchy but they do have to implement the same interface [2]. The
new language support for interfaces in C# comes in handy when implementing the
}
The encapsulation of the functionality allows clients to dynamically change algorithmic strategies by specifying the desired strategy.
Context c = new Context(new ConcreteStrategyA());
c.ContextInterface();
5 Summary
A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment.
In other words, a pattern suggests a solution to a particular problem or issue in
object-oriented software development.
In todays software development, applications and systems are complex. These
products require a great deal of flexibility in design and architecture to accommodate the ever-changing needs of clients and users during the product development
and also after the product has been released. Design patterns assist in laying the
foundation for a flexible architecture, which is the characteristic of every good
object-oriented design.
C# together with .NET brings about many benefits, including the easy-to-use
object model, the garbage collection mechanism for automatically cleaning up resources, and far improved libraries covering areas ranging from Windows GUI
support to data access and generating web pages. The .NET framework insures
that enough information is included in the compiled library files (the assemblies)
and that your classes can be inherited from and used by other .NET-aware code
without requiring access to your source files.
One of the primary goals of C# is safety; many of the problems that programmers can cause in C and C++ are avoided in C#. For example, a C# array is
guaranteed to be initialized and cannot be accessed outside of its range. The range
checking comes at the price of having a small amount of memory overhead on each
array as well as verifying the index at run-time, but the assumption is that the safety
and increased productivity is worth the expense.
A problem with C# is its close interconnection with the .NET platform. Unfortunately using this program language makes your application equally platform
dependent.
Generally the abstraction level of programming is higher in C# compared to
C++. As usual the advantages gained by raising the abstraction level, come at the
cost of lowered performance and less control.
Introducing C# in design patterns provides the programmer with a modern
object-oriented programming language offering syntactic constructs and semantic
support for concepts that map directly to notions in object-oriented design.
Design patterns suggest that you always program to an interface and not to
an implementation. Then in all of your derived classes you have more freedom to
implement methods that most suits your purposes. Since C# supports interface, this
feature is useful when implementing patterns like adapter or strategy. Delegates
and events are other well-suited features that make the design patterns cleaner.
6 References
1. Gamma E., et. al, Elements of Reusable Object-Oriented Software, AddisonWesley, 1994
2. Cooper J., Introduction to Design Patterns in C#, IBM T J Watson Research
Center, 2002
3. Shalloway A., Trott J., Design Patterns Explained: A New Perspective on
Object-Oriented Design, Addison Wesley Professional, 2001
4. Purdy D., Richter J., Exploring the Observer Design Pattern,http://msdn.
microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/obser
verpattern.asp, 2002.
5. Liberty J., Programming C#, 2nd Edition, OReilly, ISBN: 0-596-00309-9,
2002
6. Archer T., Inside C#, Microsoft Press, ISBN: 0-735-61288-9, Washington,
2001
7. Thai T., Lam H., .NET Framework Essentials, 2nd Edition, OReilly, ISBN:0596-00302-1, Sebastopol, 2002
8. Paul Kimmel, Advanced C# Programming 1st Edition, McGraw-Hill Osborne Media, ISBN 0-072-22417, September 4, 2002,
9. MSDN, C# Language specification 17. Attributes, Microsoft Corporation
2004 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
csspec/html/vclrfcsharpspec_17.asp
10. Doug Purdy, Exploring the Factory design pattern, Microsoft Corporation,
February 2002, http://msdn.microsoft.com/library/default.asp?url=/libr
ary/en-us/dnbda/html/factopattern.asp
11. MSDN Training, Introduction to C# Programming for the Microsoft .Net
Platform (Prerelease) Workbook, Course nr 2124A, march 2001
12. MSDN Library, Array Class, http://msdn.microsoft.com/library/default.a
sp?url=/library/en-us/cpref/html/frlrfSystemArrayClassTopic.asp.