Wednesday, October 13, 2010

Design Patterns – C#

C# is a modern programming language that promotes object-oriented software development by offering syntactic constructs and semantic support for concepts that map directly to notions in object-oriented design.

Singleton

class Singleton

{

private static Singleton singleton = null;

public static Singleton Instance()

{

if (null == singleton)

singleton = new Singleton();

return singleton;

}

private Singleton()

{

}

}





Strategy

interface Strategy

{

bool IsPrime(int n);

}

class Fermat : Strategy

{

public bool IsPrime(int n)

{

bool result = false;

// use Fermat's Test to determine

// if n is prime; update �result'

Console.WriteLine("Using Fermat's test");

return result;

}

}



class Primality

{

private Strategy strategy;

public Primality(Strategy s)

{

strategy = s;

}

public bool Test(int n)

{

return strategy.IsPrime(n);

}

}



Decorator



class FileTransfer

{

public virtual void Download(string url, byte[] data, int size)

{

// download the requested resource

}

public virtual void Upload(string url, byte[] data, int size)

{

// upload the requested resource

}

}



// decorated file transfer

class Decorator : FileTransfer

{

private FileTransfer ft = new FileTransfer();

private bool IsAccessAllowed(string url)

{

bool result = true;

// determine if access to the

// requested URL should be granted

return result;

}

private void LogAccess(string url)

{

// log URL, time, user identity, etc.

// to some database

Console.WriteLine("Logging access to {0}", url);

}

public override void Download(string url, byte[] data, int size)

{

if (!IsAccessAllowed(url))

return;

ft.Download(url, data, size);

LogAccess(url);

}

// similarly for Upload()

}

No comments:

Post a Comment