I would like to know what is the clear use of factory design pattern for creating an object. Can someone explain the exact benefit for using factory creation pattern with below code snippets ? I have mentioned two methods below. I would like to know is there any benefits in design perspective of using method 2 over method 1.
Method 1
class Ball {
public:
int radius;
string make;
string color;
}
class BaseBall : public Ball
{
BaseBall()
{
radius = 10;
make = "rubber"
color = "blue";
}
}
class BasketBall : public Ball
{
BasketBall()
{
radius = 10;
make = "wool"
color = "red";
}
}
//Usage
Ball *b1 = new BasketBall();
Ball *b2 = new BaseBall();
Method 2 (Factory method)
class Ball
{
public:
int radius;
string make;
string color;
};
class BallFactory
{
public:
virtual Ball* createBall();
}
class BaseBallFactory: public BallFactory
{
public:
Ball* createBall()
{
Ball *b = new Ball();
b->radius = 10;
b->make = "rubber";
b->color = "blue";
return b;
}
};
class BasketBallFactory: public BallFactory
{
public:
Ball* createBall()
{
Ball *b = new Ball();
b->radius = 10;
b->make = "wool";
b->color = "red";
return b;
}
};
//Usage
BallFactory *f1 = new BasketBallFactory();
BallFactory *f2 = new BaseBallFactory();
Ball* b1 = f1->createBall();
Ball* b2 = f2->createBall();
Aucun commentaire:
Enregistrer un commentaire