수안이의 컴퓨터 연구실

  • Mainpage
  • About Me
  • Tags
  • Metapage
  • Notice
  • Location
  • Keywords
  • Guestbook
  • Admin
  • Write an Article
  • Total | 1620972
  • Today | 352
  • Yesterday | 482

Programming/C#2007/07/27 09:18

Creational Patterns in C#

출처 : http://www.devarticles.com/c/a/c-sharp/ ··· sharp%2F

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
(Page 2 of 6 )

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
//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();
   }
}

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.

Creational Patterns in C# - The Abstract Factory Pattern
(Page 3 of 6 )

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
//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();
  }
}

Creational Patterns in C# - The Builder Pattern
(Page 4 of 6 )

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
//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);
}
}

Creational Patterns in C# - The Prototype Pattern
(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
(Page 6 of 6 )

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.

"C#" 카테고리의 다른 글
  • 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
2007/07/27 09:18 2007/07/27 09:18
Posted by webdizen
Tags C#, Pattern
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/3098

Leave your greetings.

[로그인][오픈아이디란?]

«Prev  1 ... 152 153 154 155 156 157 158 159 160 ... 2998  Next»

RSS HanRSS
Blog Image
webdizen
이 곳은 컴퓨터에 대해 연구하고, 공유하고, 소통하기 위한 연구실입니다. 개인적으로는 OLAP, Data Mining, Semantic Web, Data Modeling에 대해서 연구하고 있습니다.

Categories

전체 (2998)
Webdizen (134)
Life (6)
Diary (16)
Blog (9)
IDEA (1)
Travel (10)
Book (14)
Photo (7)
Movie (7)
Music (13)
Leisure Sports (10)
Funny (5)
Hardware (119)
Software (120)
Windows (5)
Unix & Linux (119)
Installation (4)
Kernel (10)
System (34)
Develop (22)
X-Window (0)
Applicaton (31)
Security (4)
Framework (2)
Hadoop (2)
Programming (805)
Algorithm & Data Structure (1)
Assembly (38)
UNIX/Linux C (95)
C++ (128)
STL (4)
Java (38)
Win32 API (92)
ATL/COM (44)
MFC (151)
.NET (26)
WCF/WPF (4)
C# (28)
Network Programming (17)
Database Programming (12)
OpenGL / DirectX (13)
Multimedia Programming (0)
Game Programming (21)
Parallel Distributed Progra... (0)
Reverse Engineering (0)
Debugging (9)
Python (1)
Ruby (1)
Ruby on Rails (1)
QT (4)
GTK (0)
JSP (0)
PHP (6)
ASP.NET (6)
ASP (3)
Development (28)
Useful Library (2)
Data Modeling (0)
Database (105)
Oracle (4)
MSSQL (41)
MySQL (2)
Data Warehouse (2)
Data Mining (3)
Network (66)
Web (78)
DHTML (4)
XHTML (1)
Javascript (1)
CSS (1)
AJAX (9)
XML (11)
Flex (1)
Silverlight (3)
Security (91)
DoS (1)
Kernel (10)
Scanning (3)
Sniffing (0)
Spoofing (4)
Overflow (28)
Web (11)
Shell (10)
Format String (14)
Window (2)
Embedded (70)
Multimedia (27)
Mobile (14)
Graphic (24)
Management (633)
Knowledge (581)
Hadoop (0)

Notice

  • 메타 블로그 사이트에 등록
  • 새해 맞이 블로그의 변화
  • 블로그 명칭 변경
  • 도메인(www.webdizen.net) 구...
  • TEXTCUBE 1.6.1로 업그레이드...

Tags

  • Kaist
  • Density
  • 생성자
  • Hangame
  • Ajax
  • 스마트폰
  • Resource ID
  • libpcap
  • Delayload
  • 빌 게이츠
  • 마주앙 로젤
  • ADRMS
  • Audio
  • 스킨스쿠버
  • 패킷 분석
  • Prado Framework
  • 구글
  • 퍼즐
  • 논리 로그
  • w3m

Recent Articles

  • ASCII Code의 CRLF 제거 방법.
  • Hadoop 에서 c++ API 이용시....
  • Ubuntu Linux에서 Hadoop 구....
  • 내 심장을 한껏 뛰게한 "국가....
  • 스타 스키마 데이터베이스 설....

Recent Comments

  • ■ 온라인카지노 ▶ http://L....
    asdf 11/21
  • 그리고 혹시 해외여행자보험....
    kim 11/05
  • ★★실제 바다게임장과 똑같....
    asdf 11/04
  • sbsyama.co.to← 짱5000만당....
    asdf 11/04
  • ♡KicaZ??o(???) 바카라사....
    fdsf3fass 11/03

Recent Trackbacks

  • 파일 열기/저장하기 CFileDialog.
    은마군의 나태블록 02/11
  • World IT Show 2008.
    상우 :: Oranzie's BLOG 2008
  • cvs서버 설치하기.
    3인3색 2008
  • 속속 공개되는 Google Chart....
    PHP와 Web 2.0 2007
  • 마방진을 구하는 프로그램.
    Oranzie's BLOG 3 2007

Archive

  • 2009/09 (3)
  • 2009/08 (1)
  • 2009/03 (1)
  • 2009/02 (9)
  • 2009/01 (13)

Calendar

«   2009/11   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          

Bookmarks

    • Administration
      • IIS.NET
      • NTFAQ
      • OS의 모든 것
      • 리눅스포털
    • Database
      • SQL Server Central
      • SQL Team
    • Development
      • .NET Heaven
      • ASP Alliance
      • ASP.NET 2.0
      • Bullog.net
      • C# Corner
      • C++ (C PlusPlus.com)
      • C++ Reference
      • CodeGuru
      • CodePlex
      • DebugLab
      • Dev Articles
      • Devpia
      • DotNet Junkies
      • DotNet Zone
      • Driver Online
      • GOSU.NET
      • HOONS 닷넷
      • Joinc 팀블로그
      • KOSR
      • MSDN Home Page
      • OSR Online
      • Sky.ph - 개발자 커뮤니...
      • TAEYO.NET
      • The Code Project
      • WindowsClient.net
      • 김상욱의 개발자 Side
      • 조인시 위키
    • Human Networks
      • belief21c's e-space
      • I think I can
      • Invisible Rover's Blog :D
      • Rodman®
      • ■ Feel So Good~! ■
      • 까만 나비
      • 나를 가꾸는 시간.
      • 나만의 즐거움~~!
      • 단녕
      • 상우 :: Oranzie's BLOG
    • Information Technology
      • Microsoft TechNet
      • 지디넷코리아 - 글로벌...
    • Security
      • FoundStone
      • milw0rm
      • NewOrder
      • OpenRCE
      • Phrack.org
      • Reverse Engineering b1...
      • Reverse Engineering Team
      • RootKit
      • SecurityFocus
      • SecurityXploded by Nag...
      • Wow Hacker
      • Zone-H
Textcube
Louice Studio Inc.
Powered by Textcube. Original designed by Tistory.