Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Tuesday, February 17, 2009

Interview Question asp.net 3.5 - Part 1

What do you mean by three-tier architecture?
The three-tier architecture was comes into existence to improve management of code and contents and to improve the performance of the web based applications. There are mainly three layers in three-tier architecture. the are define as follows
  1. Presentation
  2. Business Logic
  3. Database
1. First layer- Presentation contains mainly the interface code, and this is shown to user. This code could contain any technology that can be used on the client side like HTML, JavaScript or VBScript etc.

2. Second layer - is Business Logic which contains all the code of the server-side .This layer have code to interact with database and to query, manipulate, pass data to user interface and handle any input from the UI as well.

3. Third layer-Data represents the data store like MS Access, SQL Server, an XML file, an Excel file or even a text file containing data also some additional database are also added to that layers.

Do not use design patterns in any of the following situations.


When the software being designed would not change with time.
When the requirements of the source code of the application are unique.

If any of the above applies in the current software design, there is no need to apply design patterns in the current design and increase unnecessary complexity in the design.

When to use Design Patterns
Design Patterns are particularly useful in one of the following scenarios.

* When the software application would change in due course of time?

* When the application contains source code that involves object creation and event notification?

The following are some of the major advantages of using Design Patterns in software development.
  1. Flexibility
  2. Adaptability to change
  3. Reusability
What are Design Patterns?
A Design Pattern essentially consists of a problem in a software design and a solution to the same. In Design Patterns each pattern is described with its name, the motivation behind the pattern and its applicability.

According to MSDN, "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.

Happy Interview...!

Saturday, December 20, 2008

Design Pattern - Abstract Factory Pattern

Today I'm going to write about one of the most popular patterns in the design patterns world - the abstract factory.

You can read my previous posts about design patterns here:
An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.

The abstract factory dictates which products the concrete factories will produce. Each concrete factory can build different products of different types.

The only way to get the products by the client is through the factory which isolate the products definition and creation. Object creation has been abstracted and there is no need for hard-coded class names in the client code.

For an example, take a real-world demonstrates the Factory method offering flexibility in creating different documents. The derived Document classes Report and Resume instantiate extended versions of the Document class. Here, the Factory Method is called in the constructor of the Document base class.

using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatternConsole
{
/// <summary>
/// The 'Product' abstract class
/// </summary>
abstract class Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class SkillsPage : Page
{
}

/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class EducationPage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ExperiencePage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class IntroductionPage : Page
{
}


/// <summary>
/// A 'ConcreteProduct' class
/// </summary>
class ResultsPage : Page
{
}


/// <summary>
/// The 'Creator' abstract class
/// </summary>
abstract class Document
{
private List<Page> _pages = new List<Page>();

// Constructor calls abstract Factory method
public Document()
{
this.CreatePages();
}

public List<Page> Pages
{
get { return _pages; }
}

// Factory Method
public abstract void CreatePages();
}

/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Resume : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new SkillsPage());
Pages.Add(new EducationPage());
Pages.Add(new ExperiencePage());
}
}

/// <summary>
/// A 'ConcreteCreator' class
/// </summary>
class Report : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new IntroductionPage());
Pages.Add(new ResultsPage());
}
}

class AbstractFactory
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Note: constructors call Factory Method
Document[] documents = new Document[2];
documents[0] = new Resume();
documents[1] = new Report();

// Display document pages
foreach (Document document in documents)
{
Console.WriteLine("\n" + document.GetType().Name + "--");
foreach (Page page in document.Pages)
{
Console.WriteLine(" " + page.GetType().Name);
}
}

// Wait for user
Console.ReadKey();
}
}
}

Output :

The benefits of using the pattern are the isolation of concrete classes, it makes it easy to exchange product families and it makes the products consistent.

The drawback of the pattern is that the support of new products is difficult.

Happy Coding!!!

Design Pattern - Singleton

Before we move to Singleton pattern, first we should know what is instantiation and how it will play main role in Singleton.

Please refer my previous post for basic information about Design Pattern if you needs.

Instantiation means creating an object using a class as a template. There are two approaches to instantiation:
  • Lazy instantiation
  • Eager instantiation

Lazy instantiation : a class is not instantiated until a request is made via the Singleton.Instance() method.
if (singleton == null)
{
singleton = new Singleton(); // lazy instantiation
Console.WriteLine ("Singleton instantiated");
}

This code is quite simple. If singleton is null, then the Singleton object has not yet been instantiated. And, if not, it is instantiated with the new operator. This is only done once; because, the next time the code is called, singleton will not be null.

Eager instantiation is still lazy, it will run the initializers whenever the class is instantiated or another static member is accessed.

public sealed class Singleton
{

//private static Singleton singleton;
private static readonly Singleton singleton = new Singleton(); // eager instantiation

static Singleton()
{
Console.WriteLine ("Singleton instantiated");
}

private Singleton() {} // private constructor

public static Singleton GetInstance()
{
//if (singleton == null)
//{
// singleton = new Singleton();
// Console.WriteLine ("Singleton instantiated");
//}
return singleton;
}
}

The only differences between this eager code and the previous lazy example is that Singleton is instantiated in the static initializer instead of in the Singleton.Instance() method; and, there is a static constructor. However, this implementation is thread safe.


Now we will move to singleton.

Singleton is a design pattern used to restrict the instantiation of a class to one object. It is one of the most used and well know design patterns in programming.

For an example, you may need a class that will contain the user information across the system, there is no need to create several instances of this class. The explanation of this will be given in this little sample below:

Step 1. DesignPatternTest.aspx

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="DesignPatternTest.aspx.cs"
Inherits="DesignPatternTest.SingletonSample" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Singleton</title>
</head>
<body>
<form id="form1" runat="server">
<div>
See the above Singleton output
</div>
</form>
</body>
</html>

Step 2. DesignPatternTest.aspx.cs
using System;

namespace DesignPatternTest
{
public partial class SingletonSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Constructor is protected
// Prevented from using 'new' keyword
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

if (s1 == s2)
Response.Write("s1 & s2 are the same instance");

s1.x = 100;
Response.Write("<br>s1.x=" + s1.x);

s2.x = 200;
Response.Write("<br>s2.x=" + s2.x);

// Updates to x are updating same instance
Response.Write("<br>s1.x=" + s1.x);
Response.Write("<br>s2.x=" + s2.x);

}
}

public class Singleton
{
// Variable
public int x = 0;

// Fields
private static Singleton instance;

// Empty Constructor
protected Singleton() { }

// Methods
public static Singleton Instance()
{
// Uses "Lazy initialization"
if (instance == null)
instance = new Singleton();

return instance;
}
}
}

See the output

Singleton can be used in many situations, for samples.
  • Caches
  • Loggers
  • Thread pools
  • Dialog boxes
  • Device drivers
Last but not least, singleton is a class which permits itself to be instantiated only once.

  • Has a private or protected constructor with no parameters.
  • Has a single, global means of access via a static method.
  • Cannot be subclassed nor instantiated with the new operator.
  • Uses lazy instantiation

Happy Coding!!!

Wednesday, August 20, 2008

Design Patterns : An introduction

Design Patterns

Design Patterns are an essential tool for any object orientated programmer who wants to take his/her skills to the next level. Understanding the specifics of Design Pattern practices and methodologies will help developers uncover reoccurring patterns in software development and give them the tools to apply the correct solution.

Types of Design Patterns

  • Informal Design Patterns - such as the use of standard code constructs, best practice, well structured code, common sense, the accepted approach, and evolution over time.
  • Formal Design Patterns - documented with sections such as "Context", "Problem", "Solution", and a UML diagram.

Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general. Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general.

For example, some patterns provide presentation logic for displaying specific views that make up the user interface. Others control the way that the application behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses.

The following list shows some of the most common design patterns within these groups:

  • Presentation Logic
    1. Model-View-Controller (MVC)
    2. Model-View-Presenter (MVP)
    3. Use Case Controller
  • Host or Behavioral
    1. Command
    2. Publish-Subscribe / Observer
    3. Plug-in / Module / Intercepting Filter
  • Structural
    1. Service Agent / Proxy / Broker
    2. Provider / Adapter
  • Creational
    1. Factory / Builder / Injection
  • Persistence
    1. Repository

We will see how to use these pattern in the next post.

Happy programming!!!