What is the need for Factory Method in C#?

When your application has an abstract base class which is inherited by different derived classes, any derived class can be instantiated and the base class methods can be executed using that derived class instance.



Each derived class overrides the base class methods to provide a different implementation of the method. Now all that you require is a method which decides on which derived class has to be instantiated. This decision making method is known as factory method.

Here is an example:

public abstract class number {
public abstract void displayType();
}
public class oddNo:number {
public override void displayType() { Console.WriteLine(“Odd number”); }
}
public class evenNo:number {
public override void displayType() { Console.WriteLine(“Even number”); }
}
public class testClass {
public static number sampleFactoryMethod(int sampleNo) {
number num;
if(sampleNo%2==0) { num = new evenNo(); }
else { num = new oddNo(); }
return num;
}
public static void Main() {
int data = 11;
number obj = sampleFactoryMethod(data);
obj.displayType();
}
}

Output of this code will be: Odd number

In this example, sampleFactoryMethod makes the decision of which derived class instance has to be created. Hence this method implements the Factory Method Pattern in C#.

| What is Private Access Modifier in C#? | What is Protected Access Modifier in C#? | What is Protected Internal Access Modifier in C#? | What is Public Access Modifier in C#? | What is the difference between virtual and abstract keywords in .NET? | What is the importance of Microsoft Application Blocks in .NET Architecture? | What is the need for Factory Method in C# | What is the purpose of ArrayList in .NET? | What is the purpose of Datareader in ADO.NET? | What is the purpose of Dataset in ADO.NET? | What is the purpose of finally block in C#? | What is the purpose of interlocked class in .NET? | What is the purpose of main() function in C# | What is the purpose of ManualResetEvent in .NET? | What is the purpose of sealed method in C#? | What is the purpose of Thread.Join() method in .NET? | What is the purpose of Thread.Sleep() method in .NET? | What is the purpose of throw keyword in C#? | What is the usage of ENUM in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.