Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1887404
  • 博文数量: 496
  • 博客积分: 12043
  • 博客等级: 上将
  • 技术积分: 4778
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-27 14:26
文章分类

全部博文(496)

文章存档

2014年(8)

2013年(4)

2012年(181)

2011年(303)

2010年(3)

分类: C/C++

2012-06-11 09:29:13

目标:定义了一个创建一系列相关或相互依赖的接口,而无需指定它们的具体类。
           用于交换产品系列,如 ACCESS­>SQL SERVER;
           产品的具体类名被具体工厂的实现分离

示例代码:
#include
#include
#include

using namespace std;

//用户抽象接口
class IUser
{
public:
    virtual void GetUser()=0;
    virtual void InsertUser()=0;
};

//部门抽象接口
class IDepartment
{
public:
    virtual void GetDepartment()=0;
    virtual void InsertDepartment()=0;
};

//access用户
class CAccessUser : public IUser
{
public:
    virtual void GetUser()
    {
        cout << "Access GetUser" << endl;
    }
   
    virtual void InsertUser()
    {
        cout << "Access InsertUser" << endl;
    }
};

//access部门
class CAccessDepartment : public IDepartment
{
public:
    virtual void GetDepartment()
    {
        cout << "Access GetDepartment" << endl;
    }
   
    virtual void InsertDepartment()
    {
        cout << "Access InsertDepartment" << endl;
    }
};

//SQL用户
class CSqlUser : public IUser
{
public:
    virtual void GetUser()
    {
        cout << "Sql GetUser" << endl;
    }
   
    virtual void InsertUser()
    {
         cout << "Sql InsertUser" << endl;
    }
};

//SQL部门类
class CSqlDepartment : public IDepartment
{
public:
    virtual void GetDepartment()
    {
    cout << "Sql GetDepartment" << endl;
    }
   
    virtual void InsertDepartment()
    {
    cout << "Sql InsertDepartment" << endl;
    }
};

//抽象工厂
class IFactory
{
public:
    virtual IUser* CreateUser()=0;
    virtual IDepartment* CreateDepartment()=0;
};

//access工厂
class AccessFactory : public IFactory
{
public:
    virtual IUser* CreateUser()
    {
        return new CAccessUser();
    }
   
    virtual IDepartment* CreateDepartment()
    {
        return new CAccessDepartment();
    }
};

//sql工厂
class SqlFactory : public IFactory
{
public:
    virtual IUser* CreateUser()
    {
        return new CSqlUser();
    }
   
    virtual IDepartment* CreateDepartment()
    {
         return new CSqlDepartment();
    }
};

//客户端
int main()
{
    IFactory* factory = new SqlFactory();
    IUser* user = factory->CreateUser();
    IDepartment* depart = factory->CreateDepartment();
    user->GetUser();
    depart->GetDepartment();
   
    IFactory* access_factory = new AccessFactory();
    IUser* access_user = access_factory->CreateUser();
    IDepartment* access_depart = access_factory->CreateDepartment();
    access_user->GetUser();
    access_depart->GetDepartment();
   
    return 0;
}

阅读(613) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~