How do you handle shared members when dealing with interfaces?

不问归期 提交于 2020-01-17 05:03:49

问题


So I did tons and tons of work trying to make an interface for a common set of classes. The idea was to make an interface that each class could use within the set, but ultimately each class is different. Turns out interfaces do not like shared members. What I tried:

Public Interface ISomeInterface
Shared Property Meta() as Object
End Interface


Public Class A

Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery

Public Function Haduken() as Object
'perform Haduken
End Function
End Class


Public Class B

Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery

Public Function SonicBoom() as Object
'perform sonic boom
End Function
End Class

Obviously, had I done my homework on this, I would have known that shared members can't be use in interfaces. Should I just leave the individual classes completely responsible for handling its shared members? Is there another way to keep coupling down to a minimum with shared members? Theres about 20 something or so classes that will implement a single interface. Thanks in advance.


回答1:


The simplest way to work around this is to have a Private implementation of the interface which simply forwards to the Shared member

Public Shared Property Meta As Object
  ' Get / Set methods
End Property

Private Property MetaImpl() as Object Implements ISomeInterFace.Meta
  Get 
    return Meta
  End Get
  Set
    Meta = Value
  End Set
End Propery

This pattern allows you to maintain the same public facing API and still implement the interface.




回答2:


If the idea is that each implementation of the interface should use its own shared variable, JaredPar's approach is the right one. If the idea is that all users of the interface should see the same shared variable, regardless of what instance they have (if any), the right approach is to create a class with a name similar to the interface, and use a shared member of that class. That is the approach used by e.g. Enumerable<T>.Empty or Comparer<T>.Default.



来源:https://stackoverflow.com/questions/7613133/how-do-you-handle-shared-members-when-dealing-with-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!