Factory Design pattern

Factory design pattern provides you an interface creating a single object, but let subclass decide which class to instantiate. This pattern is used most frequently when we are having common functionality with different methods for different objects.

In that scenario, we will create an interface with defining common functionality which will be implemented by the classes. A class will be defined which will be used to identify which class to be instantiated for the object.

For example, We have to create reading utility and we are having 3 different kind of files 1st is pdf, 2nd is doc and 3rd is txt file. On all the files we have to perform open operation but way to open the file will be different. In this case we will create an Interface will contain OpenFile Operation. There will be classes for each file type and the classes will be implementing the factory interface(Example is given in C# Code Example.

C# Code Example:


 
///public enum to provide file type.
public enum FileType
    {
        PDF,DOC,TXT
    }

    ///public Factory Interface
    public interface IFile
    {
        void OpenFile(string FilePath);
    }

    ///Concrete Classes (Not accessible to the outside world
    class PDFFile : IFile
    {
        public void OpenFile(string FilePath)
        {
            ///Perform Action to open PDF File.
        }
    }

    class DOCFile : IFile
    {
        public void OpenFile(string FilePath)
        {
            ///Perform Action to open Doc File.
        }
    }

    class TXTFile : IFile
    {
        public void OpenFile(string FilePath)
        {
            ///Perform Action to open TXT File.
        }
    }

    ///Class to identify which class to be instantiated
    public class File
    {
     ///Method which will return File Object (User of the factory will not be aware about the class which is instantiated. 
        public static IFile GetFile(FileType Ft)
        {
            if (Ft == FileType.PDF)
                return new PDFFile();
            else if (Ft == FileType.DOC)
                return new DOCFile();
            else return new TXTFile();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IFile f = File.GetFile(FileType.PDF);
            String filePath = "";
            f.OpenFile(filePath);
        }
    }

No comments:

Post a Comment