Creational Patterns in C#
(Page 1 of 6 )
When it comes to asking questions about creating patterns with C#, Rajesh has all the answers. Read about some C# patterns in this article.
The software design patterns are mainly classified into three categories, namely Creational Patterns, Structural Patterns and Behavioral Patterns. The Creational Patterns deals with the best way to create objects. The Singleton Pattern is an example of Creational Pattern.
The singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits.
The famous GOF defined the Singleton Pattern as follows.
“Ensure a class has only one instance, and provide a global point of access to it.” -- "Design Patterns” Gamma et al., Addison-Wesley, ISBN:0-201-63361-2”
The Singleton class can be used in various places where one would need a common repository of information that can be accessed from all objects in an application. For example sometimes we may need a single Database connection object or Network connection object.
Non-software Example
The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, "The President of the United States" is a global point of access that identifies the person in the office. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]
It is pretty easy to implement the Singleton Pattern in C#. There are lots trivial ways to achieve this. But by using a private constructor and a static method to create an instance of the class is a popular way to create singleton pattern.
The above program will display OK and then followed by NO MORE OBJECTS. The value of the object sic2 is null, because we can’t create two or more instances of the class SingleInstanceClass.
C# Implementation
//Creational Pattern: SINGLETON
//Implemenation in C#
//By rajeshvs@msn.com
/*The
constructor should be private. Provide a static method, which returns
an instance of the class. use a static variable to check whether
already one instance is created or not. if already an instance is there
, returns a null */
using System;
class SingleInstanceClass
{
private static SingleInstanceClass sic= null;
private static bool instanceFlag = false;
private SingleInstanceClass()
{
}
public static SingleInstanceClass Create()
{
if(! instanceFlag)
{
sic = new SingleInstanceClass();
instanceFlag = true;
return sic;
}
else
{
return null;
}
}
protected void Finalize()
{
instanceFlag = false;
}
}
class MyClient
{
public static void Main()
{
SingleInstanceClass sic1,sic2;
sic1 = SingleInstanceClass.Create();
if(sic1 != null)
Console.WriteLine("OK");
sic2 = SingleInstanceClass.Create();
if(sic2 == null)
Console.WriteLine("NO MORE OBJECTS");
}
}
The above program returns a null value when try to create an object second time. But instead of returning null, it is possible to return already existing object ‘sic’ by changing ‘return null’ to ‘return sic’ in the above program.
Creational Patterns in C# - The Factory Method Pattern The
Factory Method Pattern comes under the classification of Creational
Patterns. The creational patterns deals with the best way to create
objects. The Factory Method provides a simple decision making class
that can return the object of one of several subclasses of an abstract
base class depending on the information that are provided. “Define
an interface for creating an object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation
to subclasses.” -- "Design Patterns” Gamma et al., Addison-Wesley,
ISBN:0-201-63361-2” Non-software Example Injection
molding presses demonstrate this pattern. Manufacturers of plastic toys
process plastic molding powder, and inject the plastic into molds of
the desired shapes. The class of toy (car, action figure, etc.) is
determined by the mold. [Michael Duell, "Non-software examples of
software design patterns", Object Magazine, Jul 97, p54] A
factory pattern is one that returns an instance of one of several
possible classes depending on the data provided to it. Usually all of
the classes it returns should have a common base class and common
methods, but implementations of the methods may be different. The
following is an UML representation of the Factory Method Pattern. In
this case we are not directly creating an instance of the class
Derived1 and Derived2. Instead we are using the getObject() method of
the Factory class to return an appropriate instance depending on the
value passed to the getObject() method. This method is commonly knows
as the Factory method and Factory method can be either static or
non-static in nature. C# Implementation //Creational Pattern: The Factory Method This
is what the fundamental principle of Factory pattern. We create an
abstraction, which decides which of several possible classes to return,
and returns one. After that we can call the methods of that class
instance without ever knowing which derived class is using actually.
The object creation happens in a single place that is inside the
Factory class. Remember that
the Factory class can contain more than one Factory methods. Even these
Factory methods can be either static or non-static. The
Abstract Factory Pattern comes under the classification of Creational
Patterns. The creational patterns deals with the best way to create
objects. The Abstract Factory provides an interface to create and
return one of several families of related objects. “Provide
an interface for creating families of related or dependent objects
without specifying their concrete classes” -- "Design Patterns” Gamma
et al., Addison-Wesley, ISBN:0-201-63361-2” Non-software Example This
pattern is found in the sheet metal stamping equipment used in the
manufacture of Japanese automobiles. The stamping equipment is an
Abstract Factory, which creates auto body parts. The same machinery is
used to stamp right hand doors, left hand doors, right front fenders,
left front fenders, hoods, etc. for different models of cars. Through
the use of rollers to change the stamping dies, the concrete classes
produced by the machinery can be changed within three minutes. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54] The
abstract factory is a factory object that returns one of several
factories. It can be used to return one of several related classes of
objects, each of which can return several different objects on request. The
abstract factory pattern can be interpreted and implemented in many
ways. The following is a simples interpretation and implementation of
this pattern. In
this case the interface Factory has two concrete implementations,
ConcreteFactory1 and ConcreteFactory2. The getObject() inside these
concrete classes returns Derived1 and Derived2 objects respectively.
The client can decide which ConcreteFactory class has to be used during
the run-times. The following
is a more complicated interpretation and implementation of this
pattern. Here those Factory class methods are used for returning
objects of two different class hierarchies. C# Implementation // Creational Pattern: Abstract Factory Pattern Creational Patterns in C# - The Builder Pattern The
Builder Pattern comes under the classification of Creational Patterns.
The creational patterns deals with the best way to create objects. The
Builder Pattern separates the construction of a complex object from its
representation so that several different representations can be created
depending on the needs of the program. “Separate
the construction of a complex object from its representation so that
the same construction process can create different representations.” ”
-- "Design Patterns” Gamma et al., Addison-Wesley, ISBN:0-201-63361-2” Builder
is an object creational design pattern that codifies the construction
process outside of the actual steps that carries out the construction -
thus allowing the construction process itself to be reused. Non-software Example Fast
food restaurants to construct children’s meals use this pattern.
Children's meals typically consist of a main item, a side item, a
drink, and a toy (e.g., a hamburger, fries, Coke, and toy car). Note
that there can be variation in the content of the children's meal, but
the construction process is the same. Whether a customer orders a
hamburger, cheeseburger, or chicken, the process is the same. The
employee at the counter directs the crew to assemble a main item, side
item, and toy. These items are then placed in a bag. The drink is
placed in a cup and remains outside of the bag. This same process is
used at competing restaurants. [Michael Duell, "Non-software examples
of software design patterns", Object Magazine, Jul 97, p54] Another
example for Builder pattern is a Computer Assembly. A computer is
nothing but the bundling of various components like FDD, HDD, Monitor
etc. But when an user buys a computer someone assemble all these
components and given to us. Remember that here the building process is
completely hidden from the client or user. The UML diagram for a Builder pattern is more or less like following one. Remember
that a project can contain one or more builders and each builder is
independent of others. This will improves the modularity and makes the
addition of other builders relatively simple. Since each builder
constructs the final product step by step, we have more control over
the final product that a builder constructs. C# Implementation //Creational Pattern: BUILDER
(Page 2 of 6 )
//Author: rajeshvs@msn.com
/*
In Factory method pattern, A Factory class contains a factory method is
used for creating the object. This factory method can be either static
or non-static. */
using System;
class Factory
{
public Base GetObject(int type)
{
Base base1 = null;
switch(type)
{
case 1:
base1 = new Derived1();
break;
case 2:
base1 = new Derived2();
break;
}
return base1;
}
}
interface Base
{
void DoIt();
}
class Derived1 : Base
{
public void DoIt()
{
Console.WriteLine("Derived 1 method");
}
}
class Derived2 : Base
{
public void DoIt()
{
Console.WriteLine("Derived 2 method");
}
}
//Client class
//Client class needn’t know about instance creation. The creation of Product is //deferred to the Factory class
class MyClient
{
public static void Main()
{
Factory factory = new Factory();//Decides which object must create.
Base obj = factory.GetObject(2);
obj.DoIt();
}
}
(Page 3 of 6 )
//Author: rajeshvs@msn.com
/*
In the following snippet, Factory is an interface. The concrete implementation of this
interface ConcreteFactory1 and ConcreteFactory2 implements the method getObject so
that it returns Derived1 and Derived2 objects respectively. The Base is an interface and
Derived1 and Derived2 are the concrete implementations of the base class. The client
(MyClient class) always uses the Factory implementations to create an instance of the
Base classes. Actually the derived classes of Factory interface decided which object
(either Derived1 or Derived2) has to be created.
*/
using System;
interface Factory
{
Base GetObject();
}
//This class is responsible for creating objects of the class Derived1.
class ConcreteFactory1 :Factory
{
public Base GetObject()
{return new Derived1();
}
}
//This class is responsible for creating objects of the class Derived2.
class ConcreteFactory2 : Factory
{
public Base GetObject()
{
return new Derived2();
}}
interface Base
{
void DoIt();
}
class Derived1 : Base
{
public void DoIt()
{
Console.WriteLine("Derived 1 method");
}
}
class Derived2 : Base
{
public void DoIt()
{
Console.WriteLine("Derived 2 method");
}
}
/*
Client class Client class needn’t know about instance creation. The creation of Product
is deferred to he ConcreteFactory1.
*/
class MyClient
{
public static void Main()
{
Factory factory = new ConcreteFactory2();//Decides which object must create.
Base obj = factory.GetObject();
obj.DoIt();
}
}
(Page 4 of 6 )
//Author: rajeshvs@msn.com
using System;
class Director
{
public void Construct(IBuilder builder)
{
builder.DoIt();
}
}
interface IBuilder
{
void DoIt();
}
class BuilderA : IBuilder
{
public void DoIt()
{
//Necessary code for building the computer type A
Console.WriteLine("Assembly a Computer with mono monitor");
}
}
class BuilderB : IBuilder
{
public void DoIt()
{
//Necessary code for building the computer type B
Console.WriteLine("Assembly a Computer with color monitor");
}
}
class MyClient
{
public static void Main()
{
Director d = new Director();
IBuilder build = new BuilderA();
d.Construct(build);
}
}
(Page 5 of 6 )
The Prototype Pattern comes under the classification of Creational Patterns. The creational patterns deals with the best way to create objects. This helps to copy or clone the existing objects to create new ones rather than creating from the scratch.
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. -- "Design Patterns” Gamma et al., Addison-Wesley, ISBN:0-201-63361-2”
The prototype pattern is used when creating an instance of a class is very time consuming or complex in some way. Then rather than creating more instances, it is possible to make copies of the original instances and modifying them as appropriate.
When we are not in a position to call a constructor for an object directly, we could alternatively clone a pre-existing object (a prototype) of the same class. When there are many subclasses that differ only in the kind of objects they create a Prototype Pattern can be used to reduce the number of subclasses by cloning a prototype. Prototype Design Pattern helps in reducing number of classes.
For example suppose we have to do say Sales Analysis on a set of data in the database. Normally we will create an object encapsulating this data and do the Sales Analysis. Suppose now we have to do another type of analysis say Promotion Analysis on the same data. Now instead of creating another object corresponds to the data from the scratch, we can clone the existing object and do the analysis. This is one of the classical use of prototype pattern.
Remember that in C#, this pattern can be implemented easily by using the clone(). Any class, which wants to support cloning, should inherit from the ICloneable interface in C#. ICloneable interface contains a Clone() method which we can override in our class. Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.
The resulting clone must be of the same type as or a compatible type to the original instance.
Creational Patterns in C# - Summary The Singleton Pattern
is a pattern that insures there are one and only one instance of an
object, and that it is possible to obtain global access to that one
instance. The Factory Pattern is used to choose and return an instance of a class from a number of similar classes based on data you provide to the factory. The Abstract Factory
Pattern is used to return one of several groups of classes. In some
cases it actually returns a Factory for that group of classes. The Builder Pattern
assembles a number of objects to make a new object, based on the data
with which it is presented. Frequently, the choice of which way the
objects are assembled is achieved using a Factory. The Prototype Pattern copies or clones an existing class rather than creating a new instance when creating new instances is more expensive.
(Page 6 of 6 )
- Introduction to Objects and Classes in C# (0)2007/07/27
- Creational Patterns in C# (0)2007/07/27
- Exception Handling in C# (0)2007/07/27
- C# 키워드 목록 (0)2007/07/02
- Event Handling in .NET Using C# (0)2007/06/26

수안이의 컴퓨터 연구실







Leave your greetings.