lundi 16 septembre 2019

Factory pattern returning same instance

Let's take an example "factory" class written in C#:

public class HasherFactory : IHasherFactory
{
    private readonly Sha1Hasher _sha1Hasher;
    private readonly Sha2Hasher _sha2Hasher;

    public HasherFactory(Sha1Hasher sha1Hasher, Sha2Hasher sha2Hasher)
    {
        _sha1Hasher = sha1Hasher;
        _sha2Hasher = sha2Hasher;
    }

    public IHasher CreateHasher(string hashAlgorithm)
    {
        switch (hashAlgorithm.ToLower())
        {
            case "sha1":
                return _sha1Hasher;
            case "sha2":
                return _sha2Hasher;
            default:
                throw new ArgumentException("Invalid hash algorithm", nameof(hashAlgorithm));
        }
    }
}

The problem I have here is the naming convention of this class. Factory suggests that each execution of CreateHasher will return a new instance, but it is not the case. What is the pattern used here called?

Aucun commentaire:

Enregistrer un commentaire