-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path抽象工厂模式.cs
99 lines (93 loc) · 2.41 KB
/
抽象工厂模式.cs
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
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace DesignMode
{
/// <summary>
/// 提供一个创建一系列相关或依赖对象的的接口
/// 而无需指定它们具体的类
/// </summary>
public class 抽象工厂模式
{
[Fact]
public void Test()
{
User user = new User();
IFactory factory = new SqlserverFactory();
IUser iu = factory.CreateUser();
iu.Insert(user);
iu.GetUser(1);
}
/// <summary>
/// 定义一个创建访问User表对象的抽象的工厂接口
/// </summary>
interface IFactory
{
IUser CreateUser();
}
/// <summary>
/// 实例化SqlserverUser
/// </summary>
class SqlserverFactory : IFactory
{
public IUser CreateUser()
{
return new SqlserverUser();
}
}
/// <summary>
/// 实例化AccessUser
/// </summary>
class AccessFactory : IFactory
{
public IUser CreateUser()
{
return new AccessUser();
}
}
/// <summary>
/// 用户客户端访问,解除与具体数据库访问的耦合
/// </summary>
interface IUser
{
void Insert(User user);
User GetUser(int id);
}
/// <summary>
/// sqlserver具体类
/// </summary>
class SqlserverUser : IUser
{
public void Insert(User user)
{
Console.WriteLine("sqlserver 新增一条数据");
}
public User GetUser(int id)
{
Console.WriteLine("sqlserver 获取一条数据");
return null;
}
}
/// <summary>
/// Access具体类
/// </summary>
class AccessUser : IUser
{
public User GetUser(int id)
{
Console.WriteLine("Access 获取一条数据");
return null;
}
public void Insert(User user)
{
Console.WriteLine("Access 新增一条数据");
}
}
class User
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}