The Factory Pattern in C# is a creational design pattern that provides an interface for creating objects but allows subclasses to alter the type of objects that will be created. It's often used in situations where a class cannot anticipate the type of objects it needs to create, or when a class wants to delegate the responsibility of object creation to its subclasses. Here's an example of the Factory Pattern in C#, followed by five examples of its use:
1.Vehicle Factory:
Imagine you are building a transportation simulation application, and you need to create various types of vehicles, such as cars, bicycles, and motorcycles. You can use a factory to create instances of these vehicles based on user input.
public interface IVehicle
{
void Drive();
}
public class Car : IVehicle
{
public void Drive()
{
Console.WriteLine("Driving a car...");
}
}
public class Bicycle : IVehicle
{
public void Drive()
{
Console.WriteLine("Riding a bicycle...");
}
}
public class VehicleFactory
{
public IVehicle CreateVehicle(string vehicleType)
{
switch (vehicleType.ToLower())
{
case "car":
return new Car();
case "bicycle":
return new Bicycle();
default:
throw new ArgumentException("Invalid vehicle type.");
}
}
}
2. Payment Gateway Factory:
If you're developing an e-commerce system, you might need to integrate with different payment gateways (e.g., PayPal, Stripe, Square). A factory can create instances of payment gateway classes based on the selected payment method.
public interface IPaymentGateway
{
void ProcessPayment(double amount);
}
public class PayPalGateway : IPaymentGateway
{
public void ProcessPayment(double amount)
{
Console.WriteLine($"Processing ${amount} payment using PayPal...");
}
}
public class StripeGateway : IPaymentGateway
{
public void ProcessPayment(double amount)
{
Console.WriteLine($"Processing ${amount} payment using Stripe...");
}
}
public class PaymentGatewayFactory
{
public IPaymentGateway CreateGateway(string paymentMethod)
{
switch (paymentMethod.ToLower())
{
case "paypal":
return new PayPalGateway();
case "stripe":
return new StripeGateway();
default:
throw new ArgumentException("Invalid payment method.");
}
}
}
public interface INotificationService
{
void SendNotification(string message);
}
public class EmailService : INotificationService
{
public void SendNotification(string message)
{
Console.WriteLine($"Sending email: {message}");
}
}
public class SMSService : INotificationService
{
public void SendNotification(string message)
{
Console.WriteLine($"Sending SMS: {message}");
}
}
public class NotificationServiceFactory
{
public INotificationService CreateService(string serviceType)
{
switch (serviceType.ToLower())
{
case "email":
return new EmailService();
case "sms":
return new SMSService();
default:
throw new ArgumentException("Invalid notification service.");
}
}
}
0 Comments