抽象工厂模式提供了一个创建一系列相关或互相依赖对象的接口,而无需指定它们的具体类。
当你在进行数据库开发的时候,刚开始用的是sql server数据库,所以你把有关数据库的内容都封成一个类,那么如果以后换成access了呢?难道要再把access的用法封成一个类?就算这个类封好了,那外部程序中有关sql server的代码不是都要改成access的代码了吗?这个时候当然是用到工厂模式啦,当然,不过因为对数据库的操作涉及到很多不同的表,所以这个模式称之为抽象工厂模式,其实也就是先定义一个抽象的工厂接口,把数据库中相同的表也抽象出来,然后再在对应的具体工厂中实现对具体表的操作,看代码吧:
#include <iostream>
#include <string>
using namespace std;
class method_user
{
public:
virtual void insert( string user_name ) {}
virtual void get_id_message( int id ) {}
};
class sql_method_user : public method_user
{
public:
void insert( string user_name )
{
cout << "在sql server中往user表中插入" << user_name << endl;
}
void get_id_message( int id )
{
cout << "sql server中id号为" << id << "的信息是" << endl;
}
};
class access_method_user : public method_user
{
public:
void insert( string user_name )
{
cout << "在access中往user表中插入" << user_name << endl;
}
void get_id_message( int id )
{
cout << "access中id号为" << id << "的信息是" << endl;
}
};
class method_department
{
public:
virtual void insert( string department_name ) {}
virtual void get_id_message( int id ) {}
};
class sql_method_department : public method_department
{
public:
void insert( string department_name )
{
cout << "要往sql的department表中插入" << department_name << endl;
}
void get_id_message( int id )
{
cout << "sql中department表中id为" << id << "的信息是" << endl;
}
};
class access_method_department : public method_department
{
public:
void insert( string department_name )
{
cout << "要往access的department表中插入" << department_name << endl;
}
void get_id_message( int id )
{
cout << "access中department表中id为" << id << "的信息是" << endl;
}
};
class factory
{
public:
virtual method_user *user() {}
virtual method_department *department() {}
};
class sql_factory : public factory
{
public:
method_user *user()
{
return new sql_method_user;
}
method_department *department()
{
return new sql_method_department;
}
};
class access_factory : public factory
{
public:
method_user *user()
{
return new access_method_user;
}
method_department *department()
{
return new access_method_department;
}
};
int main()
{
factory *f = new sql_factory;
method_user *u1 = f->user();
method_department *d1 = f->department();
u1->insert( "杨大少爷" );
u1->get_id_message( 23 );
d1->insert( "人事部" );
factory *f2 = new access_factory;
method_department *d2 = f2->department();
d2->insert( "放学社" );
}