文章

写给大家看的设计模式

抽象工厂模式

  1. 被创建抽象类 Iuser;
  2. 抽象工厂类 IFactory,定义创建接口 IUser* createUser()。 当需要新增被创建类型时,需要新增被创建类型及对应工厂类型;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// 代表数据库中User表中的一条记录
class RecUser {
  int32_t uid;
  std::string uname;
};

// 代表数据库中Department表中一条记录
class RecDepartment {
  int32_t did;
  std::string dname;
};

// 1. 用户表操作抽象接口
class IUser {
public:
  virtual void insert(const RecUser *user) = 0;
  virtual RecUser *getUserRecord(int32_t id) = 0;
  virtual ~IUser() = default;
};

// 2.1 User表操作实现类:SQL Server
class SqlServerUser : public IUser {
public:
  void insert(const RecUser *user) override {
    std::cout << "Insert a user record into SQL Server table." << std::endl;
  }
  RecUser *getUserRecord(int32_t id) override {
    std::cout << "Get a record from SQL Server table." << std::endl;
    return nullptr;
  }
  ~SqlServerUser() override {
    std::cout << "dtor of SqlServerUser." << std::endl;
  }
};

// 2.2 User表操作实现类:access 表
class AccessUser : public IUser {
public:
  void insert(const RecUser *user) override {
    std::cout << "Insert a user record into access table." << std::endl;
  }
  RecUser *getUserRecord(int32_t id) override {
    std::cout << "Get a record from access table." << std::endl;
    return nullptr;
  }
  ~AccessUser() override {
    std::cout << "dtor of AccessUser. " << std::endl;
  }
};

// 3. 抽象工厂类
class IFactory {
public:
  virtual IUser *createUser() = 0;
};

// 4.1 SQL Server 具体工厂类
class SqlFactory : public IFactory {
public:
  IUser *createUser() override {
    return new SqlServerUser;
  }
};

// 4.2 access 具体工厂类
class AccessFactory : public IFactory {
public:
  IUser *createUser() override {
    return new AccessUser;
  }
};

TEST_CASE("design mode: abstract factory") {
  RecUser user_rec;

  // 创建类型1实例:SQL表操作
  std::shared_ptr<IFactory> factory(new SqlFactory);
  std::shared_ptr<IUser> user_table(factory->createUser());
  user_table->insert(&user_rec);
  user_table->getUserRecord(1);

  // 创建类型2实例:access表操作
  factory.reset(new AccessFactory);
  user_table.reset(factory->createUser());
  user_table->insert(&user_rec);
  user_table->getUserRecord(1);
}
本文由作者按照 CC BY 4.0 进行授权