定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Ball
{
public:
virtual void Play() = 0;
};
class Basketball : public Ball
{
public:
virtual void Play()
{
cout<<"play Basketball"<<endl;
}
};
class Football : public Ball
{
public:
virtual void Play()
{
cout<<"play Football"<<endl;
}
};
class Factory
{
public:
virtual Ball* CreateBall() = 0;
};
class BasketballFactory : public Factory
{
public:
virtual Ball* CreateBall()
{
return new Basketball;
}
};
class FootballFactory : public Factory
{
public:
virtual Ball* CreateBall()
{
return new Football;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Factory* factory = new BasketballFactory;
Ball* ball = factory->CreateBall();
ball->Play();
Factory* factory1 = new BasketballFactory;
Ball* ball1 = factory->CreateBall();
ball1->Play();
return 0;
}
工厂方法将创建细分到具体的子类,是一种解耦的方法,是增加创建类型变得比较容易而且不用修改之前的代码,抽象工厂对增加并不是封闭的