ramlicious Blogs by Tina & Prabhu

September 26, 2011

Implementation of Factory Pattern

Filed under: .NET,C#,Design Patterns,Programming — Prabhuram @ 1:33 pm

I bundled together from my older examples to show the Factory design pattern here. This is an  implementation of one of the object library I created to search for a given text within files of different type  namely a text, xml or excel file. The library uses factory pattern to create an instance of the object required based on the request.


Here the Product is Seeker, Concrete Products are TextSeeker, XmlSeeker and ExcelSeeker. The Factory class is the SeekerFactory.

And you can simply use it from a client like this (you can use any XML file and change the properties accordingly):

    class Program
    {
        static void Main(string[] args)
        {
            SearchEntity a = new
                XmlFileSearchEntity() { RecurringElement = "url", LookupElement = "loc", SourceName = @"C:\OnWeb\sitemap.xml", SearchString = "prabhuram" };
            Seeker helper = new SeekerFactory().CreateXmlSeeker();

            foreach (Match match in helper.Search(a))
                Console.WriteLine(match.SearchString + "-" + match.MatchType.ToString() + "-" + match.PositionX + "," + match.PositionY + "-" + match.MatchingText);
            Console.ReadKey();
        }
    }

You can download the complete project from here: SearchLibrary.zip

This is simply how a Factory works. Other creational patterns like Factory Method and Abstract Factory  demonstrate a slight variation to the Factory pattern.

Powered by WordPress