避免需要建立连接的类中的时间耦合

问题描述 投票:0回答:1

我正在设计一个类,提供与蓝牙设备交互的方法。 我的设计大致是这样的:

class Device
{
    private bool _isConnected;
    private readonly ulong _bluetoothAddress;

    public Device(ulong bluetoothAddress)
    {
        _bluetoothAddress = bluetoothAddress;
    }

    public async Task ConnectAsync()
    {
        // Async connection logic...

        _isConnected = true;
    }

    public async Task SendMessage(Message message)
    {
        if (!_isConnected)
        {
            throw new InvalidOperationException("Not connected");
        }

        // Send logic...
    }
}

我不喜欢这个设计的地方是它在 API 中引入了时间耦合。客户始终需要在

ConnectAsync
之前致电
SendMessage

c# oop design-patterns
1个回答
0
投票

这个怎么样?

if (!_isConnected)
{
    await ConnectAsync();
}
© www.soinside.com 2019 - 2024. All rights reserved.