一,抽象工厂模式
(1.假设这里有三个工厂 :中国工厂,美国工厂,日本工厂
(2.中国工厂生产:中国香蕉,中国苹果
美国工厂生产:美国香蕉,美国苹果
日本工厂生产:日本香蕉,日本苹果
(3.将中国工厂 美国工厂 日本 工厂抽象出来
将中国香蕉 美国香蕉 日本香蕉抽象出来。苹果也抽象出来 得到抽象的香蕉和苹果。
二,抽象工厂模式图示
图1:
图2:
三,抽象工厂模式代码实现
#include <iostream>
using namespace std;
//抽象苹果
class AbstractApple
{
public:
virtual void showName()=0;
AbstractApple()
{
cout<<"*抽象苹果构造"<<endl;
}
~AbstractApple()
{
cout<<"*抽象苹果析构"<<endl;
}
};
//抽象香蕉
class AbstractBanana
{
public:
virtual void showName()=0;
AbstractBanana()
{
cout<<"*抽象香蕉构造"<<endl;
}
~AbstractBanana()
{
cout<<"*抽象香蕉析构"<<endl;
}
};
class ChinaApple :public AbstractApple
{
public:
virtual void showName()
{
cout<<"i am Chinese apple"<<endl;
}
ChinaApple()
{
cout<<"中国苹果构造"<<endl;
}
~ChinaApple()
{
cout<<"中国苹果析构"<<endl;
}
protected:
private:
};
class AmericApple :public AbstractApple
{
public:
virtual void showName()
{
cout<<"i am American Apple"<<endl;
}
AmericApple()
{
cout<<"美国苹果构造"<<endl;
}
~AmericApple()
{
cout<<"美国苹果析构"<<endl;
}
protected:
private:
};
class AmericBanana :public AbstractBanana
{
public:
virtual void showName()
{
cout<<"i am American banana"<<endl;
}
AmericBanana()
{
cout<<"美国香蕉构造"<<endl;
}
~AmericBanana()
{
cout<<"美国香蕉析构"<<endl;
}
protected:
private:
};
class ChinaBanana :public AbstractBanana
{
public:
virtual void showName()
{
cout<<"i am Chinese banana"<<endl;
}
ChinaBanana()
{
cout<<"中国香蕉构造"<<endl;
}
~ChinaBanana()
{
cout<<"中国香蕉析构"<<endl;
}
protected:
private:
};
//抽象工厂 针对产品转换
class AbstractFactory
{
public:
virtual AbstractApple* CreateApple()=0;
virtual AbstractBanana* CreateBanana()=0;
AbstractFactory()
{
cout<<"*抽象工厂构造"<<endl;
}
~AbstractFactory()
{
cout<<"*抽象工厂析构"<<endl;
}
};
class ChinaFactory:public AbstractFactory
{
public:
virtual AbstractApple* CreateApple()
{
return new ChinaApple;
};
virtual AbstractBanana* CreateBanana()
{
return new ChinaBanana;
};
ChinaFactory()
{
cout<<"中国工厂构造"<<endl;
}
~ChinaFactory()
{
cout<<"中国工厂析构"<<endl;
}
};
class AmericanFactory:public AbstractFactory
{
public:
virtual AbstractApple* CreateApple()
{
return new AmericApple;
};
virtual AbstractBanana* CreateBanana()
{
return new AmericBanana;
};
AmericanFactory()
{
cout<<"美国工厂构造"<<endl;
}
~AmericanFactory()
{
cout<<"美国工厂析构"<<endl;
}
};
int main()
{
{
AbstractFactory* t_factory = new ChinaFactory;
AbstractApple* t_absApple = t_factory->CreateApple();
AbstractBanana* t_absBanana = t_factory->CreateBanana();
t_absApple->showName();
t_absBanana->showName();
delete t_absBanana;
t_absBanana = nullptr;
delete t_absApple;
t_absApple = nullptr;
delete t_factory;
t_factory = nullptr;
}
cout<<"---------------------------"<<endl;
{
AbstractFactory* t_factory = new AmericanFactory;
AbstractApple* t_absApple = t_factory->CreateApple();
AbstractBanana* t_absBanana = t_factory->CreateBanana();
t_absApple->showName();
t_absBanana->showName();
delete t_absBanana;
t_absBanana = nullptr;
delete t_absApple;
t_absApple = nullptr;
delete t_factory;
t_factory = nullptr;
}
system("pause");
return 0;
}