✅ Factory method

like i sincerely don’t understand this concept. could someone elaborate?
2 Replies
Merineth 🇸🇪
Merineth 🇸🇪OP3mo ago
// 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.
}
}
// 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.
}
}
does it imply that we put the new in a different class and not in the main program? Would that be all?
Yuta chiharu
Yuta chiharu3mo ago
yes ...i think we use factory for loose coupling and many more things example if you create the object directly and now you need to change your car to raceCar we cant do that but with factory we can acheive that by simply changing the return new Car() to return new raceCar() if any wrong someone teach me too😅
Want results from more Discord servers?
Add your server