Factory Pattern in C#
Quick Answer
The Factory Pattern in C# is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It promotes loose coupling and enhances code maintainability by encapsulating object creation logic.
Learning Objectives
- Explain the purpose of Factory Pattern in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Factory Pattern.
- Apply Factory Pattern in a simple real-world scenario or practice task.
Introduction
Design patterns are proven solutions to common software design problems. The Factory Pattern is one of the fundamental creational patterns in C#.
It helps manage object creation by abstracting the instantiation process, making your code more flexible and easier to maintain.
Encapsulate object creation to promote loose coupling.
What is the Factory Pattern?
The Factory Pattern defines an interface for creating an object but lets subclasses decide which class to instantiate.
This pattern delegates the responsibility of object instantiation to subclasses, promoting flexibility and scalability.
- Separates object creation from usage.
- Supports open/closed principle by allowing new types without modifying existing code.
- Improves code maintainability and readability.
When to Use the Factory Pattern
Use the Factory Pattern when your code needs to create objects without specifying the exact class of the object to be created.
It is especially useful when the system needs to be independent of how its objects are created, composed, and represented.
- When a class can't anticipate the class of objects it must create.
- When subclasses should specify the objects to be created.
- To centralize object creation logic.
Implementing the Factory Pattern in C#
The Factory Pattern typically involves a factory class with a method that returns different types of objects based on input parameters or logic.
Below is a simple example demonstrating the pattern.
Example: Shape Factory
Consider a scenario where you want to create different shapes like Circle and Rectangle without exposing the instantiation logic to the client.
Practical Example
This example defines an interface IShape and two implementations: Circle and Rectangle. The ShapeFactory class has a method GetShape that returns an instance of the requested shape. The client code uses the factory to get shape objects without knowing their concrete classes.
Examples
public interface IShape {
void Draw();
}
public class Circle : IShape {
public void Draw() {
Console.WriteLine("Drawing a Circle");
}
}
public class Rectangle : IShape {
public void Draw() {
Console.WriteLine("Drawing a Rectangle");
}
}
public class ShapeFactory {
public IShape GetShape(string shapeType) {
if (shapeType == null) return null;
if (shapeType.Equals("CIRCLE", StringComparison.OrdinalIgnoreCase)) {
return new Circle();
} else if (shapeType.Equals("RECTANGLE", StringComparison.OrdinalIgnoreCase)) {
return new Rectangle();
}
return null;
}
}
// Usage
class Program {
static void Main() {
ShapeFactory factory = new ShapeFactory();
IShape shape1 = factory.GetShape("CIRCLE");
shape1.Draw();
IShape shape2 = factory.GetShape("RECTANGLE");
shape2.Draw();
}
}This example defines an interface IShape and two implementations: Circle and Rectangle. The ShapeFactory class has a method GetShape that returns an instance of the requested shape. The client code uses the factory to get shape objects without knowing their concrete classes.
Best Practices
- Use interfaces or abstract classes for the products created by the factory.
- Keep the factory method focused on object creation only.
- Avoid complex logic inside the factory method; delegate if necessary.
- Use the Factory Pattern to adhere to the Open/Closed Principle.
- Document the factory's behavior clearly for maintainability.
Common Mistakes
- Creating too many factory classes unnecessarily.
- Putting business logic inside the factory instead of just object creation.
- Returning null without handling it properly in client code.
- Not using interfaces or abstractions for created objects.
- Overcomplicating the factory method with unrelated responsibilities.
Hands-on Exercise
Implement a Vehicle Factory
Create a factory class that can instantiate different types of vehicles like Car, Bike, and Truck implementing a common interface IVehicle with a method Drive().
Expected output: Console output showing the Drive() method being called on different vehicle instances.
Hint: Define an IVehicle interface and concrete classes for each vehicle type. Implement a factory method that returns the correct vehicle based on input.
Interview Questions
What is the Factory Pattern and why is it used?
InterviewThe Factory Pattern is a creational design pattern that abstracts the process of object creation. It is used to create objects without specifying the exact class of the object to be created, promoting loose coupling and flexibility.
How does the Factory Pattern promote the Open/Closed Principle?
InterviewBy encapsulating object creation in a factory, new product types can be added by extending the factory without modifying existing client code, thus adhering to the Open/Closed Principle.
What is the difference between Factory Method and Abstract Factory patterns?
InterviewThe Factory Method pattern uses inheritance to decide which class to instantiate, while the Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
MCQ Quiz
1. What is the best first step when learning Factory Pattern?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Factory Pattern?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. The Factory Pattern in C# is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.
B. Factory Pattern never needs examples
C. Factory Pattern is unrelated to practical work
D. Factory Pattern should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- The Factory Pattern in C# is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.
- It promotes loose coupling and enhances code maintainability by encapsulating object creation logic.
- Design patterns are proven solutions to common software design problems.
- The Factory Pattern is one of the fundamental creational patterns in C#.
- It helps manage object creation by abstracting the instantiation process, making your code more flexible and easier to maintain.
Summary
The Factory Pattern is a powerful creational design pattern in C# that abstracts object creation.
It helps in writing flexible, maintainable, and scalable code by decoupling the client from concrete classes.
Understanding and applying this pattern is essential for designing robust software systems.
Frequently Asked Questions
Can the Factory Pattern be used with abstract classes instead of interfaces?
Yes, the Factory Pattern can use abstract classes or interfaces as the product type. The key is to have a common abstraction for the objects created.
Is the Factory Pattern the same as the Singleton Pattern?
No, the Factory Pattern focuses on object creation abstraction, while the Singleton Pattern ensures a class has only one instance.
Does the Factory Pattern always require a separate factory class?
Not necessarily. Sometimes the factory method can be part of an existing class, but having a separate factory class improves separation of concerns.
What is Factory Pattern?
The Factory Pattern in C# is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.
Why is Factory Pattern important?
It promotes loose coupling and enhances code maintainability by encapsulating object creation logic.
How should I practice Factory Pattern?
Design patterns are proven solutions to common software design problems.

