Skip to content

Factory pattern

Jiufen edited this page Apr 19, 2021 · 1 revision

๐ŸŒž Introduction ๐ŸŒž

The factory pattern is a pattern that handle the instatiation of our objects in one single place(class). This help us by not having the instantiations spread all over our scripts, not knowing where a certain object is instantiated.

๐Ÿ”จ How it works? ๐Ÿ”จ

In unity/c# we can implement the factory pattern by having a factory that will instantiate a certain implementation of an abstract class that we choose, something like this:

๐ŸŒ€ Example ๐ŸŒ€

In our example we will examine an ability system, so it will look something like this:

The ability factory will have a constructor that will search for every Ability in our assembly and then create a dictionary pointing the name(i.e fire) with the type (FireAbility.cs).

public AbilityFactory(){
    var abilityTypes = Assembly.GetAssembly(typeof(Ability)).GetTypes().
                           Where(myType => !myType.IsAbstract && myType.IsSubclassOf(typeof(Ability)));

    abilitiesByName = new Dictionary();

    foreach (var type in abilityTypes)
    {
        var tempEffect = Activator.CreateInstance(type) as Ability;
        abilitiesByName.Add(tempEffect.Name, type);
    }
}

Then when we want to search for a certain class to instantiate all we do is as the dictionary and if it exist, we instantiated:

public Ability GetAbility(string abilityType){
    if(abilitiesByName.ContainsKey(abilityType)){
        Type type = abilitiesByName[abilityType];
        var ability = Activator.CreateInstance(type) as Ability;
        return ability;
    }
    return null;
}

The benefit of having all of this objects descend from an abstract class is that when we isntantiate them, we can assing a Proccess method, that will execute for each class. For example:

public class FireAbility : Ability
{
    public override string Name => "Fire";

    public override void Process() {
        Debug.Log("Fire Creation");
    }
}

Clone this wiki locally