Factory
The factory pattern is one of the simpler patterns you will come across. Its purpose is to hide the underlying creation mechanism for a class so you can create something in an isolated way and get an implementation you need without having to worry about actually initializing it yourself.

Getting started

For example if we had some classes like:
1
public enum AnimalType
2
{
3
Unknown = 0,
4
Dog = 1,
5
Cat = 2
6
}
7
8
public interface Animal
9
{
10
string MakeSound();
11
}
12
13
public class Dog : Animal
14
{
15
public string MakeSound()
16
{ return "woof woof"; }
17
}
18
19
public class Cat : Animal
20
{
21
public string MakeSound()
22
{ return "meow meow"; }
23
}
Copied!
Then if we wanted to get an animal based upon the type we could make a factory like so:
1
public class AnimalFactory()
2
{
3
public IAnimal CreateAnimal(AnimalType type)
4
{
5
switch(type)
6
{
7
case AnimalType.Dog: { return new Dog(); }
8
default: { return new Cat(); }
9
}
10
}
11
}
Copied!
That is a basic factory which would generate the implementations you require without you having to worry about how it does it.

Example usage

1
var animalFactory = new AnimalFactory();
2
var myAnimal = animalFactory.CreateAnimal(AnimalType.Dog);
3
4
Console.WriteLine(myAnimal.MakeSound());
Copied!
Historically factory patterns used to be used a lot to abstract away hardware resources, like textures, vertex buffers etc. As when you were making a cross platform engine and needed to work with OpenGL, DirectX (or other rendering technologies) the developer rarely cared about the underlying hardware, they just wanted a texture of a certain size to use, or a vertex buffer of a certain size to provide to the renderer, so this pattern helped abstract away these concerns and exposing high level objects to represend the underlying resources.
Last modified 2yr ago