jeudi 25 février 2016

Factory's claims and passing it arguments to initialize objects it creates

Factory pattern brings two main things to the table:

  • Detaches client side code from exact implementation details of classes.
  • Centralize code creation so if the creation logic changes, it is changed only in the factory instead of possible 20 files.

But what if I want to pass specific arguments to the constructor to initialize it properly? This would come from user or current state of the application. Wouldn't this kind of defeat the 2nd point?

class AnimalFactory
{
public:
    createAnimal(type, string nickName)
    {
        if (type == 0)
            return new Dog(nickName);
        else if(type == 1)
            return new Cat(nickName);
    }
}

The above is how I have seen in examples, but is the following equally good factory, perhaps even more preferable since its more readable and pass one less argument?

class AnimalFactory
{
public:
    createDog(string nickName)
    {
        return new Dog(nickName);
    }

    createCat(string nickName)
    {
        return new Cat(nickName);
    }
}

Aucun commentaire:

Enregistrer un commentaire