The Factory Pattern is a creational design pattern that provides an interface for creating objects in a super class, but allows subclasses to alter the type of objects that will be created. Here's an example of the Factory Pattern in C#:
Let's say we have an interface called `IVehicle`:
```csharp
public interface IVehicle
{
void Drive();
}
We have two classes implementing this interface: `Car` and `Motorcycle`:
```csharp
public class Car : IVehicle
{
public void Drive()
{
Console.WriteLine("Driving the car.");
}
}
public class Motorcycle : IVehicle
{
public void Drive()
{
Console.WriteLine("Riding the motorcycle.");
}
}
Now, let's create a `VehicleFactory` class that acts as the factory for creating objects of `IVehicle`:
```csharp
public class VehicleFactory
{
public IVehicle CreateVehicle(string vehicleType)
{
if (vehicleType.Equals("Car", StringComparison.OrdinalIgnoreCase))
{
return new Car();
}
else if (vehicleType.Equals("Motorcycle", StringComparison.OrdinalIgnoreCase))
{
return new Motorcycle();
}
else
{
throw new ArgumentException("Invalid vehicle type");
}
}
}
```
In this example, `VehicleFactory` is the factory class responsible for creating objects of `IVehicle`. It has a method `CreateVehicle` that takes a string representing the type of vehicle and returns an object of `IVehicle`.
Here's how you can use the Factory Pattern:
csharp
class Program
{
static void Main(string[] args)
{
VehicleFactory vehicleFactory = new VehicleFactory();
Console.WriteLine("Enter vehicle type (Car/Motorcycle): ");
string vehicleType = Console.ReadLine();
IVehicle vehicle = vehicleFactory.CreateVehicle(vehicleType);
vehicle.Drive();
Console.ReadLine();
}
}
In this example, the user is prompted to enter a vehicle type (either "Car" or "Motorcycle"). The `VehicleFactory` creates an object of the corresponding type, and the `Drive` method of the created object is called without needing to know the specific class of the object. This demonstrates the use of the Factory Pattern to create objects based on user input.
No comments:
Post a Comment
Comments Welcome