// A general toy class
abstract class Toy
{
public abstract void Play();
}
// Specific types of toys
class Car : Toy
{
public override void Play()
{
Console.WriteLine("Vroom! I'm a car.");
}
}
class Doll : Toy
{
public override void Play()
{
Console.WriteLine("Hi! I'm a doll.");
}
}
// The factory method
abstract class ToyFactory
{
public abstract Toy CreateToy();
}
class CarFactory : ToyFactory
{
public override Toy CreateToy()
{
return new Car();
}
}
class DollFactory : ToyFactory
{
public override Toy CreateToy()
{
return new Doll();
}
}
// Using the factory method
class Program
{
static void Main(string[] args)
{
ToyFactory carFactory = new CarFactory();
Toy car = carFactory.CreateToy();
car.Play(); // Output: Vroom! I'm a car.
ToyFactory dollFactory = new DollFactory();
Toy doll = dollFactory.CreateToy();
doll.Play(); // Output: Hi! I'm a doll.
}
}