Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
The Factory Pattern in C# is a structural approach that belongs to the category of design patterns. Factory method design pattern in C# is aimed at solving problems related to creating objects without specifying the exact creator class of the object that will be created.
Essentially, factory pattern deals with object creation by delegating it to a specific class, known as the factory class. This enables a system to be more flexible and easier to manage, especially when introducing new types of objects, as the factory class handles the object creation process, reducing the dependency on the concrete classes. Let's dive into how the factory method pattern, a creational design pattern in C# can be implemented and used. We'll explore the IronPDF library later.
The core idea behind the factory method pattern is to define a common interface for creating objects while allowing subclasses to change the type of objects they create. This pattern involves a few key components: abstract factory pattern, creational design patterns, factory design pattern, existing code, basic factory pattern, abstract factory patterns, real-world examples, concrete product, related or dependent objects, and concrete class.
Consider a scenario where we have different types of vehicles like cars and trucks. We'll use the factory pattern to create a vehicle factory that can create different types of vehicles based on user input or a configuration file.
public interface IVehicle
{
void DisplayInfo();
}
public interface IVehicle
{
void DisplayInfo();
}
Public Interface IVehicle
Sub DisplayInfo()
End Interface
public class Car : IVehicle
{
public void DisplayInfo()
{
Console.WriteLine("This is a Car.");
}
}
public class Truck : IVehicle
{
public void DisplayInfo()
{
Console.WriteLine("This is a Truck.");
}
}
public class Car : IVehicle
{
public void DisplayInfo()
{
Console.WriteLine("This is a Car.");
}
}
public class Truck : IVehicle
{
public void DisplayInfo()
{
Console.WriteLine("This is a Truck.");
}
}
Public Class Car
Implements IVehicle
Public Sub DisplayInfo()
Console.WriteLine("This is a Car.")
End Sub
End Class
Public Class Truck
Implements IVehicle
Public Sub DisplayInfo()
Console.WriteLine("This is a Truck.")
End Sub
End Class
public abstract class VehicleFactory
{
public abstract IVehicle CreateVehicle(string type);
}
public abstract class VehicleFactory
{
public abstract IVehicle CreateVehicle(string type);
}
Public MustInherit Class VehicleFactory
Public MustOverride Function CreateVehicle(ByVal type As String) As IVehicle
End Class
public class ConcreteVehicleFactory : VehicleFactory
{
public override IVehicle CreateVehicle(string type)
{
switch (type.ToLower())
{
case "car": return new Car();
case "truck": return new Truck();
default: throw new ArgumentException("Invalid vehicle type");
}
}
}
public class ConcreteVehicleFactory : VehicleFactory
{
public override IVehicle CreateVehicle(string type)
{
switch (type.ToLower())
{
case "car": return new Car();
case "truck": return new Truck();
default: throw new ArgumentException("Invalid vehicle type");
}
}
}
Public Class ConcreteVehicleFactory
Inherits VehicleFactory
Public Overrides Function CreateVehicle(ByVal type As String) As IVehicle
Select Case type.ToLower()
Case "car"
Return New Car()
Case "truck"
Return New Truck()
Case Else
Throw New ArgumentException("Invalid vehicle type")
End Select
End Function
End Class
class Program
{
static void Main(string [] args)
{
// create objects
VehicleFactory factory = new ConcreteVehicleFactory();
IVehicle car = factory.CreateVehicle("car");
car.DisplayInfo();
IVehicle truck = factory.CreateVehicle("truck");
truck.DisplayInfo();
}
}
class Program
{
static void Main(string [] args)
{
// create objects
VehicleFactory factory = new ConcreteVehicleFactory();
IVehicle car = factory.CreateVehicle("car");
car.DisplayInfo();
IVehicle truck = factory.CreateVehicle("truck");
truck.DisplayInfo();
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
' create objects
Dim factory As VehicleFactory = New ConcreteVehicleFactory()
Dim car As IVehicle = factory.CreateVehicle("car")
car.DisplayInfo()
Dim truck As IVehicle = factory.CreateVehicle("truck")
truck.DisplayInfo()
End Sub
End Class
In the above example, the VehicleFactory class serves as the abstract creator, with the ConcreteVehicleFactory class being the concrete creator that implements the factory method CreateVehicle. This method decides which type of vehicle to create based on the input it receives. The client code then uses the factory to create instances of different vehicles, promoting loose coupling between the object creation logic and the client code.
The factory pattern offers several advantages, especially in complex systems:
IronPDF is a library designed for the .NET platform, helping developers easily create, edit, and manipulate PDF files directly from HTML, CSS, images, and JavaScript, without diving into complex PDF generation APIs. Its main attraction lies in its ability to transform web content into PDF documents swiftly and with high accuracy, thanks to its use of a Chrome-based rendering engine.
Key features include generating PDFs from HTML strings or URLs, rendering web pages as PDFs on the fly, and the ability to work with forms applications, server applications, and secure intranets among others. Its performance is optimized for efficiency, with capabilities for asynchronous operations, custom logging, and extensive documentation to help get you started quickly.
To illustrate how IronPDF can be integrated with the Factory Pattern, let's create a simplified example. The Factory Pattern is a type of creational design pattern that offers a way to create concrete products or objects within a superclass, permitting subclasses to modify the specific objects being produced. This fits well with creating different types of PDF documents based on specific needs, such as from HTML strings, URLs, or files.
We'll create an interface named IPdfCreator that defines a method for creating PDFs, and then implement different factory classes that create PDFs in various ways using IronPDF.
This interface declares the CreatePdf method that all concrete factories will implement.
public interface IPdfCreator
{
void CreatePdf(string source);
}
public interface IPdfCreator
{
void CreatePdf(string source);
}
Public Interface IPdfCreator
Sub CreatePdf(ByVal source As String)
End Interface
Here we define two concrete implementations of IPdfCreator: one for creating PDFs from HTML strings and another from URLs.
// public class
public class HtmlStringPdfCreator : IPdfCreator
{
public void CreatePdf(string htmlString)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlString);
pdf.SaveAs("HtmlStringPdf.pdf");
}
}
public class UrlPdfCreator : IPdfCreator
{
public void CreatePdf(string url)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs("UrlPdf.pdf");
}
}
// public class
public class HtmlStringPdfCreator : IPdfCreator
{
public void CreatePdf(string htmlString)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlString);
pdf.SaveAs("HtmlStringPdf.pdf");
}
}
public class UrlPdfCreator : IPdfCreator
{
public void CreatePdf(string url)
{
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf(url);
pdf.SaveAs("UrlPdf.pdf");
}
}
' public class
Public Class HtmlStringPdfCreator
Implements IPdfCreator
Public Sub CreatePdf(ByVal htmlString As String)
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlString)
pdf.SaveAs("HtmlStringPdf.pdf")
End Sub
End Class
Public Class UrlPdfCreator
Implements IPdfCreator
Public Sub CreatePdf(ByVal url As String)
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf(url)
pdf.SaveAs("UrlPdf.pdf")
End Sub
End Class
In your application, you can now use these factories to create PDF documents from different sources without worrying about the details of the PDF creation process.
class Program
{
static void Main(string [] args)
{
License.LicenseKey = "License-Key";
IPdfCreator htmlPdfCreator = new HtmlStringPdfCreator();
htmlPdfCreator.CreatePdf("<h1>Hello, World!</h1>");
IPdfCreator urlPdfCreator = new UrlPdfCreator();
urlPdfCreator.CreatePdf("http://example.com");
}
}
class Program
{
static void Main(string [] args)
{
License.LicenseKey = "License-Key";
IPdfCreator htmlPdfCreator = new HtmlStringPdfCreator();
htmlPdfCreator.CreatePdf("<h1>Hello, World!</h1>");
IPdfCreator urlPdfCreator = new UrlPdfCreator();
urlPdfCreator.CreatePdf("http://example.com");
}
}
Friend Class Program
Shared Sub Main(ByVal args() As String)
License.LicenseKey = "License-Key"
Dim htmlPdfCreator As IPdfCreator = New HtmlStringPdfCreator()
htmlPdfCreator.CreatePdf("<h1>Hello, World!</h1>")
Dim urlPdfCreator As IPdfCreator = New UrlPdfCreator()
urlPdfCreator.CreatePdf("http://example.com")
End Sub
End Class
In this setup, HtmlStringPdfCreator and UrlPdfCreator are concrete factories that produce PDFs. The Program class, acting as a client, uses these factories without needing to know the intricate details of how PDFs are generated from HTML strings or URLs. This approach provides flexibility, as you can introduce new ways of creating PDFs (e.g., from files or streams) simply by adding more factories that implement the IPdfCreator interface, following the Open/Closed Principle of object-oriented design.
The following screenshots are the output of the code:
The factory pattern in C# provides a framework for managing object creation, making software design more maintainable and extensible. By using concrete classes to implement an abstract factory and delegate creation logic, developers can create systems that are easier to adapt and expand. Whether dealing with a few classes or a system with complex dependencies, the factory pattern offers a structured approach to exact class object creation. It's particularly beneficial in scenarios where the type of objects to be created can vary based on user input, configuration, or application state.
IronPDF offers a free trial to get started, and license options begin at $749, catering to developers looking to integrate PDF functionalities into their .NET applications.
9 .NET API products for your office documents