samedi 2 avril 2016

Passing value in factory pattern

I am learning factory design pattern. I am not able to figure out how we can pass parameters to object created using Factory pattern.

One Small Silly Example:

Suppose I have three class, Class A and class B and Class Number. Number being the base class. Also, class A expects three integers and has functionality to add them and class B expects two integer and adds them

Code Snippet:

int main()
{

    Factory *facObj = new Factory();
    // Addition for Two Integers
    Number * numberObjOne = facObj->createObj("AddThreeInteger");
    Number * numberObjTwo = facObj->createObj("AddTwoInteger");
}

Factory.cpp

Number * Factory::createObj(string str)
{
    if (str == "AddThreeInteger")
    {
        return new A(1,2,3);
    }
    else if (str == "AddTwoInteger")
    {
        return new B(1,2);
    }
    else            
        return NULL;
}

Question: Now no matter what I do I can only add the hard coded numbers. How do I pass these integers value from my Client code or from main(). Its a silly example and I am new to programming. Kindly help me here. How can I not hardcode the value and get the results. Can I somwhow pass the values at facObj->createObj Am I making sense? Kindly help me.

Aucun commentaire:

Enregistrer un commentaire