-
Notifications
You must be signed in to change notification settings - Fork 31
/
Adapter.cs
107 lines (93 loc) · 2.4 KB
/
Adapter.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
100
101
102
103
104
105
106
107
namespace DesignPatterns.Structural;
using MAmp = int;
using Amp = decimal;
public class Adapter
{
[Fact]
public void Execute()
{
const int maxUsbPower = 200;
var phone = new Phone(maxUsbPower);
Assert.False(phone.IsCharging);
var outlet = new AcOutlet(15);
var adapter = new UsbAdapter(outlet, maxUsbPower);
phone.ConnectTo(adapter);
Assert.True(phone.IsCharging);
var badAdapter = new BadUsbAdapter(outlet);
Assert.Throws<OverflowException>(() => phone.ConnectTo(badAdapter));
}
/// <summary>
/// Client
/// </summary>
/// <remarks>
/// Collaborates with objects conforming to the Target interface.
/// </remarks>
public class Phone(MAmp maxMAmps)
{
private MAmp _mAmps;
public bool IsCharging => _mAmps > 0;
public void ConnectTo(IUsbSocket socket)
{
MAmp mAmps = socket.GetPower();
if (mAmps > maxMAmps)
{
throw new OverflowException();
}
_mAmps = mAmps;
}
}
/// <summary>
/// Target
/// </summary>
/// <remarks>
/// Defines the domain-specific interface that Client uses.
/// </remarks>
public interface IUsbSocket
{
MAmp GetPower();
}
/// <summary>
/// Adaptee
/// </summary>
/// <remarks>
/// Defines an existing interface that needs adapting.
/// </remarks>
public interface IAcSocket
{
Amp GetPower();
}
/// <inheritdoc />
public class AcOutlet(Amp amps) : IAcSocket
{
public Amp GetPower() => amps;
}
/// <summary>
/// Adapter
/// </summary>
/// <remarks>
/// Adapts the interface Adaptee to the Target interface.
/// </remarks>
public class UsbAdapter(IAcSocket socket, MAmp maxMAmps) : IUsbSocket
{
public MAmp GetPower()
{
Amp amps = socket.GetPower();
var mAmps = (MAmp)(amps * 100);
return Math.Min(maxMAmps, mAmps);
}
}
/// <summary>
/// Adapter
/// </summary>
/// <remarks>
/// Adapts the interface Adaptee to the Target interface.
/// </remarks>
public class BadUsbAdapter(IAcSocket socket) : IUsbSocket
{
public MAmp GetPower()
{
Amp amps = socket.GetPower();
return (MAmp)(amps * 100);
}
}
}