抽象工厂模式最大的好处是,易于交换,在一个应用中只需要new出一个抽象工厂,提供实例化,就可以根据需求改变工厂,生成不同的产品配置,而且还可以更新数据的访问。
与此同时,产品的具体类名也被具体工厂实现分离了,不会出现在客户端代码。
两个层次都依赖于抽象层,更灵活地运用了多态。
抽象工厂很方便数据的更新,也运用了依赖倒转原则和开闭原则,但是在增加功能的同时,需要运用更多的代码量,也对抽象的工厂,增加了一部分代码。给具体实现的工厂类,也需要进行改动。
#include<iostream>
#include<string>
using namespace std;
class User
{
public:
User() {}
User(string name, int id)
{
this->name = name;
this->id = id;
}
string name;
int id;
};
class Department
{
public:
Department() {}
Department(string bumen, string name)
{
this->bumen = bumen;
this->name = name;
}
string bumen;
string name;
};
//以上两个类是数据类
//2个数据类获取信息的抽象方法
class IUser
{
public:
virtual void Insert(User user) = 0;
virtual User GetUser(int id) = 0;
};
class IDdepartment
{
public:
virtual void Insert(Department de) = 0;
virtual Department GetDepa(string bumen) = 0;
};
//数据库内容的具体实现,让其依赖于抽象
class SqlserverUser : public IUser
{
public:
virtual void Insert(User user)
{
cout << "在SQL Server 中给User表增加一条记录" << "name= " << user.name << endl;
}
virtual User GetUser(int id)
{
cout << "在SQL Server 中根据ID得到一条记录" << endl;
return User();
}
};
class AccessUser : public IUser
{
//用于访问Access的表,不同数据库的多态表现形式
public:
virtual void Insert(User user)
{
cout << "在Access 中给User表增加一条记录 name =" << user.name << endl;
}
virtual User GetUser(int id)
{
cout << "在 Access 中根据ID:得到一条记录" << endl;
return User();
}
};
//都依赖于抽象接口的具体实现
class SqlserverDepartment : public IDdepartment
{
public:
virtual void Insert(Department de)
{
cout << "在SQL Server 中给Department表增加一条记录name=zzzzzzzzzzzz" << endl;
}
virtual Department GetDepa(string bumen)
{
cout << "在SQL Server 中给Department表增加一条记录" << endl;
return Department();
}
};
class AccessDepartment : public IDdepartment
{
public:
virtual void Insert(Department de)
{
cout << "在Access 中给Department表增加一条记录" << " name =" << de.name << " 部门是" << de.bumen << endl;
}
virtual Department GetDepa(string bumen)
{
cout << "在Accessr 中给Department表增加一条记录" << endl;
return Department();
}
};
//访问抽象库IUser的抽象工厂接口类
class IFactory
{
public:
virtual IUser* CreateUser() = 0;//名字和ID数据
virtual IDdepartment* CreteDepartment() = 0;//部门数据
};
class SqlserverFactory : public IFactory
{
public:
IUser* CreateUser()
{
return new SqlserverUser;
}
IDdepartment* CreteDepartment()
{
return new SqlserverDepartment;
}
};
class AccessFactory : public IFactory
{
public:
IUser* CreateUser()
{
return new AccessUser;
}
IDdepartment* CreteDepartment()
{
return new AccessDepartment;
}
};
int main()
{
User user("小菜", 12);
IFactory *factory = new SqlserverFactory();
IUser * iu = factory->CreateUser();
iu->Insert(user);
iu->GetUser(1);
Department de("信息部", "小菜鸟");
factory = new AccessFactory();
IDdepartment* dd = factory->CreteDepartment();
dd->Insert(de);
}