类图如下:
代码如下:
#include<iostream>
#include<string>
using namespace std;
//数据库 有Sqlserver Access 两个
//表 两个 有User表,Department表,
//假设只有两个字段,name和id
//两个数据单独定义两个类 User Department
//对数据不进行具体处理,只是进行打印
class User{
public:
void SetID(int id){
m_id=id;
}
int GetID(){
return m_id;
}
void SetName(string name){
m_name=name;
}
string GetName(){
return m_name;
}
private:
int m_id;
string m_name;
};
class Department{
public:
void SetID(int id){
m_id=id;
}
int GetID(){
return m_id;
}
void SetName(string name){
m_name=name;
}
string GetName(){
return m_name;
}
private:
int m_id;
string m_name;
};
class IUser{
public:
virtual void Insert(User user)=0;
virtual User GetUser(int id)=0;
virtual ~IUser(){
}
};
class SqlserverUser:public IUser{
public:
void Insert(User user){
cout<<"在Sqlserver 中给User表增加一条记录\n";
}
User GetUser(int id){
cout<<"在Sqlserver 中根据ID 得到User表一条记录\n";
User temp;
return temp;
}
};
class AccessUser:public IUser{
public:
void Insert(User user){
cout<<"在Access 中给User表增加一条记录\n";
}
User GetUser(int id){
cout<<"在Access 中根据ID 得到User表一条记录\n";
User temp;
return temp;
}
};
class IDepartment{
public:
virtual void Insert(Department user)=0;
virtual Department GetDepartment(int id)=0;
virtual ~IDepartment(){
}
};
class SqlserverDepartment:public IDepartment{
public:
void Insert(Department user){
cout<<"在Sqlserver 中给Department表增加一条记录\n";
}
Department GetDepartment(int id){
cout<<"在Sqlserver 中根据ID 得到Department表一条记录\n";
Department temp;
return temp;
}
};
class AccessDepartment:public IDepartment{
public:
void Insert(Department user){
cout<<"在Access 中给Department表增加一条记录\n";
}
Department GetDepartment(int id){
cout<<"在Access 中根据ID 得到Department表一条记录\n";
Department temp;
return temp;
}
};
//工厂类
class SimpleFactory{
public:
SimpleFactory(){
m_dbname="Sqlserver";
}
IUser* CreateUser(){
if(m_dbname=="Sqlserver")
return new SqlserverUser();
else if(m_dbname == "Access")
return new AccessUser();
else
return NULL;
}
IDepartment* CreateDepartment(){
if(m_dbname=="Sqlserver")
return new SqlserverDepartment();
else if(m_dbname == "Access")
return new AccessDepartment();
else
return NULL;
}
private:
string m_dbname;
};
int main(){
User temp_user;
Department temp_department;
SimpleFactory *factory =new SimpleFactory();
IUser*user =factory->CreateUser();
IDepartment* department=factory->CreateDepartment();
delete factory;
user->Insert(temp_user);
user->GetUser(1);
delete user;
department->Insert(temp_department);
department->GetDepartment(1);
delete department;
}