Viv*_*Dev 3 c# design-patterns decorator
我定义了一个接口,其中定义了一个事件和一个属性,如下所示。
public interface IMyInterface
{
event EventHandler SomeEvent;
string GetName();
string IpAddress { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个类并使用它,一切正常。
现在我想使用装饰器扩展这个类。我不知道如何处理该事件。对于财产我想我很清楚,只是想确认一下。
我定义装饰器类如下。
public class LoggerDecorator : IMyInterface
{
private readonly IMyInterface _MyInterface;
private readonly ILog _MyLog;
public LoggerDecorator(IMyInterface myInterface, ILog myLog)
{
if (myInterface == null)
throw new ArgumentNullException("IMyInterface is null");
_MyInterface = myInterface;
if (myLog == null)
throw new ArgumentNullException("ILog instance is null");
_MyLog = myLog;
}
public string GetName()
{
// If needed I can use log here
_MyLog.Info("GetName method is called.");
return _MyInterface.GetName();
}
// Is this the way to set properties?
public string IpAddress
{
get
{
return _MyInterface.IpAddress;
}
set
{
// If needed I can use log here
_MyLog.Info("IpAddress is set.");
_MyInterface.IpAddress = value;
}
}
// But How to handle this evetn?? Please help. I am not clear about this.
public event EventHandler SomeEvent;
}
Run Code Online (Sandbox Code Playgroud)
Bat*_*ias 10
add
您可以使用和将事件的订阅和取消订阅转发到正在装饰的元素remove
。这样,如果您订阅LoggerDecorator.SomeEvent
,您实际上订阅了内部IMyInterface.SomeEvent
。
在你的情况下,它应该看起来像这样:
public class LoggerDecorator : IMyInterface
{
(...)
public event EventHandler SomeEvent
{
add => _MyInterface.SomeEvent += value;
remove => _MyInterface.SomeEvent -= value;
}
}
Run Code Online (Sandbox Code Playgroud)