Zum Fußzeileninhalt springen
.NET HILFE

Fabrikmuster C# (Funktionsweise für Entwickler)

The Factory Pattern in C# is a structural approach that belongs to the category of design patterns. The 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, the 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 PDF Generation Library later.

Basic Factory Method Pattern Structure

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:

  • Product Interface: Specifies the structure of objects created by the factory method.
  • Concrete Product Classes: Implement the product interface.
  • Creator Class (Abstract Class Creator): Declares the factory method, which returns an object of the product interface.
  • Concrete Creator: Modifies the factory method to deliver an instance of the concrete product.

Example: Vehicle Factory

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.

Step 1: Define the Product Interface

public interface IVehicle
{
    // Method to display information about the vehicle
    void DisplayInfo();
}
public interface IVehicle
{
    // Method to display information about the vehicle
    void DisplayInfo();
}
Public Interface IVehicle
	' Method to display information about the vehicle
	Sub DisplayInfo()
End Interface
$vbLabelText   $csharpLabel

Step 2: Implement Concrete Products

public class Car : IVehicle
{
    // Displays Car specific information
    public void DisplayInfo()
    {
        Console.WriteLine("This is a Car.");
    }
}

public class Truck : IVehicle
{
    // Displays Truck specific information
    public void DisplayInfo()
    {
        Console.WriteLine("This is a Truck.");
    }
}
public class Car : IVehicle
{
    // Displays Car specific information
    public void DisplayInfo()
    {
        Console.WriteLine("This is a Car.");
    }
}

public class Truck : IVehicle
{
    // Displays Truck specific information
    public void DisplayInfo()
    {
        Console.WriteLine("This is a Truck.");
    }
}
Public Class Car
	Implements IVehicle

	' Displays Car specific information
	Public Sub DisplayInfo()
		Console.WriteLine("This is a Car.")
	End Sub
End Class

Public Class Truck
	Implements IVehicle

	' Displays Truck specific information
	Public Sub DisplayInfo()
		Console.WriteLine("This is a Truck.")
	End Sub
End Class
$vbLabelText   $csharpLabel

Step 3: Create the Abstract Creator Class

public abstract class VehicleFactory
{
    // Factory Method to create a vehicle instance
    public abstract IVehicle CreateVehicle(string type);
}
public abstract class VehicleFactory
{
    // Factory Method to create a vehicle instance
    public abstract IVehicle CreateVehicle(string type);
}
Public MustInherit Class VehicleFactory
	' Factory Method to create a vehicle instance
	Public MustOverride Function CreateVehicle(ByVal type As String) As IVehicle
End Class
$vbLabelText   $csharpLabel

Step 4: Implement the Concrete Creator

public class ConcreteVehicleFactory : VehicleFactory
{
    public override IVehicle CreateVehicle(string type)
    {
        // Create vehicle based on 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)
    {
        // Create vehicle based on 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
		' Create vehicle based on type
		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
$vbLabelText   $csharpLabel

Step 5: Client Code Usage

class Program
{
    static void Main(string[] args)
    {
        // Create factory instance
        VehicleFactory factory = new ConcreteVehicleFactory();

        // Create a Car and display its info
        IVehicle car = factory.CreateVehicle("car");
        car.DisplayInfo();

        // Create a Truck and display its info
        IVehicle truck = factory.CreateVehicle("truck");
        truck.DisplayInfo();
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Create factory instance
        VehicleFactory factory = new ConcreteVehicleFactory();

        // Create a Car and display its info
        IVehicle car = factory.CreateVehicle("car");
        car.DisplayInfo();

        // Create a Truck and display its info
        IVehicle truck = factory.CreateVehicle("truck");
        truck.DisplayInfo();
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create factory instance
		Dim factory As VehicleFactory = New ConcreteVehicleFactory()

		' Create a Car and display its info
		Dim car As IVehicle = factory.CreateVehicle("car")
		car.DisplayInfo()

		' Create a Truck and display its info
		Dim truck As IVehicle = factory.CreateVehicle("truck")
		truck.DisplayInfo()
	End Sub
End Class
$vbLabelText   $csharpLabel

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.

Factory Pattern C# (How It Works For Developers): Figure 1 - Factory Design Pattern Output

Advantages of Using the Factory Pattern

The factory pattern offers several advantages, especially in complex systems:

  • Loose Coupling: The client code interacts with interfaces or abstract classes instead of concrete product classes. This results in a design that is more flexible and easier to modify.
  • Reusable Object-Oriented Software: The factory pattern promotes the reuse of code as it separates the object creation logic from the system, making the system easier to maintain and extend.
  • Flexibility in Object Creation: The factory method allows different implementations for creating objects, which can be selected at runtime. This is especially useful in scenarios where the type of objects required can vary based on external factors.

IronPDF: .NET PDF Solution

Factory Pattern C# (How It Works For Developers): Figure 2 - IronPDF

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.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Initialize a Pdf Renderer with a Chrome Rendering Engine
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Initialize a Pdf Renderer with a Chrome Rendering Engine
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize a Pdf Renderer with a Chrome Rendering Engine
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Code Example

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.

Step 1: Define the IPdfCreator Interface

This interface declares the CreatePdf method that all concrete factories will implement.

public interface IPdfCreator
{
    // Method responsible for creating a PDF
    void CreatePdf(string source);
}
public interface IPdfCreator
{
    // Method responsible for creating a PDF
    void CreatePdf(string source);
}
Public Interface IPdfCreator
	' Method responsible for creating a PDF
	Sub CreatePdf(ByVal source As String)
End Interface
$vbLabelText   $csharpLabel

Step 2: Implement Concrete Factories

Here we define two concrete implementations of IPdfCreator: one for creating PDFs from HTML strings and another from URLs.

public class HtmlStringPdfCreator : IPdfCreator
{
    // Creates a PDF from an HTML string
    public void CreatePdf(string htmlString)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlString);
        pdf.SaveAs("HtmlStringPdf.pdf");
    }
}

// Create PDF from a given URL
public class UrlPdfCreator : IPdfCreator
{
    public void CreatePdf(string url)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderUrlAsPdf(url);
        pdf.SaveAs("UrlPdf.pdf");
    }
}
public class HtmlStringPdfCreator : IPdfCreator
{
    // Creates a PDF from an HTML string
    public void CreatePdf(string htmlString)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlString);
        pdf.SaveAs("HtmlStringPdf.pdf");
    }
}

// Create PDF from a given URL
public class UrlPdfCreator : IPdfCreator
{
    public void CreatePdf(string url)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderUrlAsPdf(url);
        pdf.SaveAs("UrlPdf.pdf");
    }
}
Public Class HtmlStringPdfCreator
	Implements IPdfCreator

	' Creates a PDF from an HTML string
	Public Sub CreatePdf(ByVal htmlString As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(htmlString)
		pdf.SaveAs("HtmlStringPdf.pdf")
	End Sub
End Class

' Create PDF from a given URL
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
$vbLabelText   $csharpLabel

Step 3: Using the Factory

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)
    {
        // Add your IronPDF license key
        License.LicenseKey = "License-Key";

        // Create PDF from HTML string
        IPdfCreator htmlPdfCreator = new HtmlStringPdfCreator();
        htmlPdfCreator.CreatePdf("<h1>Hello, World!</h1>");

        // Create PDF from URL
        IPdfCreator urlPdfCreator = new UrlPdfCreator();
        urlPdfCreator.CreatePdf("http://example.com");
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Add your IronPDF license key
        License.LicenseKey = "License-Key";

        // Create PDF from HTML string
        IPdfCreator htmlPdfCreator = new HtmlStringPdfCreator();
        htmlPdfCreator.CreatePdf("<h1>Hello, World!</h1>");

        // Create PDF from URL
        IPdfCreator urlPdfCreator = new UrlPdfCreator();
        urlPdfCreator.CreatePdf("http://example.com");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Add your IronPDF license key
		License.LicenseKey = "License-Key"

		' Create PDF from HTML string
		Dim htmlPdfCreator As IPdfCreator = New HtmlStringPdfCreator()
		htmlPdfCreator.CreatePdf("<h1>Hello, World!</h1>")

		' Create PDF from URL
		Dim urlPdfCreator As IPdfCreator = New UrlPdfCreator()
		urlPdfCreator.CreatePdf("http://example.com")
	End Sub
End Class
$vbLabelText   $csharpLabel

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.

Output

The following screenshots are the output of the code:

Factory Pattern C# (How It Works For Developers): Figure 3 - Factory Design Pattern PDF Output

Factory Pattern C# (How It Works For Developers): Figure 4 - Base Factory Method Output

Conclusion

Factory Pattern C# (How It Works For Developers): Figure 5 - Licensing

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 of IronPDF to get started, and license options begin at liteLicense, catering to developers looking to integrate PDF functionalities into their .NET applications.

Häufig gestellte Fragen

Wie kann das Factory Pattern in der C#-Entwicklung angewendet werden?

Das Factory Pattern kann in der C#-Entwicklung angewendet werden, indem eine Fabrik-Klasse erstellt wird, die die Instanziierung von Objekten verwaltet. Dieser Ansatz erlaubt es Entwicklern, eine Schnittstelle zur Erstellung eines Objekts zu definieren, während Unterklassen den Objekt-Typ ändern können, der erstellt wird, was zu lose gekoppelter und flexibler Software führt.

Welche Rolle spielt das Factory Pattern im Softwaredesign?

Das Factory Pattern spielt eine entscheidende Rolle im Softwaredesign, indem es eine Möglichkeit bietet, die Instanziierung von Objekten einer Fabrik-Klasse zu überlassen. Dies hilft, die Erstellung von Logik von der Geschäftlogik zu trennen, wodurch das System handlicher und einfacher erweiterbar wird.

Wie können Entwickler IronPDF verwenden, um PDF-Dokumente in C# zu erstellen?

Entwickler können IronPDF verwenden, um PDF-Dokumente in C# zu erstellen, indem sie seine auf Chrome basierende Rendering-Engine nutzen. Durch Methoden wie RenderHtmlAsPdf oder RenderUrlAsPdf können HTML-Strings oder Webseiten mühelos in hochwertige PDF-Dokumente umgewandelt werden.

Welche Vorteile bietet eine .NET PDF-Bibliothek wie IronPDF?

Die Verwendung einer .NET PDF-Bibliothek wie IronPDF bietet zahlreiche Vorteile, einschließlich der Möglichkeit, PDFs aus verschiedenen Eingaben wie HTML, CSS, Bildern und JavaScript zu erstellen, zu bearbeiten und zu manipulieren. Sie unterstützt asynchrone Operationen und trägt dazu bei, das ursprüngliche Layout und die Styles des Webinhalts in den PDFs beizubehalten.

Wie kann das Factory Pattern die PDF-Dokumentenerstellung verbessern?

Das Factory Pattern verbessert die PDF-Dokumentenerstellung, indem es Entwicklern ermöglicht, eine gemeinsame Schnittstelle zur Erstellung von PDFs aus verschiedenen Quellen, wie HTML-Strings, URLs oder Dateien, zu definieren. Dies ermöglicht das Hinzufügen neuer PDF-Typen, ohne den bestehenden Code zu ändern, und hält sich an das Open/Closed Principle.

In welchen Szenarien ist das Factory Pattern am nützlichsten?

Das Factory Pattern ist am nützlichsten in Szenarien, in denen ein System die Objekterstellung dynamisch, basierend auf Benutzereingaben oder Konfiguration handhaben muss. Es ist besonders vorteilhaft in Anwendungen, die häufige Änderungen oder Erweiterungen des Objekterstellungsprozesses erfordern.

Was ist die Bedeutung des Factory Patterns zur Aufrechterhaltung der Softwareflexibilität?

Die Bedeutung des Factory Patterns zur Aufrechterhaltung der Softwareflexibilität liegt in seiner Fähigkeit, die Objekterstellung von der Geschäftlogik zu trennen. Dies ermöglicht es Entwicklern, neue Objekttypen einzuführen, ohne den bestehenden Code zu ändern, was zu einer flexiblen und erweiterbaren Architektur führt.

Wie unterstützt IronPDF das Factory Pattern bei der Dokumentenerstellung?

IronPDF unterstützt das Factory Pattern bei der Dokumentenerstellung, indem es Entwicklern ermöglicht, das Muster durch seine Schnittstellen und Methoden zu implementieren. Zum Beispiel können Entwickler mit ChromePdfRenderer und verschiedenen Eingabetypen verschiedene PDF-Dokumentformen erstellen, ohne die zugrunde liegende Erstellungslösung zu ändern.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen