c# - Alternative to static methods for interface -


i understand static methods not correct interfaces (see: why doesn't c# allow static methods implement interface?) yet have come against situation have object implements methods of interface can static, think must designing incorrectly.

trouble is, cant see alternative

my interface idataserializer implemented several classes. 1 de/serializes xml, 1 json, etc. of these classes implement same functions , none have "state data" (members, etc), result in same type of object being output.

for example, xml class:

public class myxmlserializer : idataserializer {     public string serializefoo(object foo)     {          // uses .net xml serialzer serialize foo     }      public object deserializefoo(string foo)     {          // uses .net xml serializer deserialize foo     }      // object type returned above methods ever      // used following method returns type available      // idataserializer implementations      // data used rest of program      public ilist<bar> createbarlist(object deserializedfoo)     {          // magic extract list of bar          // deserialized data, main work          // idataserializer implementation     } } 

obviously of methods shown above could static (they take in info need parameters , return result of working, there no members or fields)... because should implemented in serializer can work type of serial data (xml,json, yaml, etc) form interface... it? thinking wrong? there alternative, specific, pattern achieving want do?

afterthought: maybe should change idea of de/serialization being work can do thinking of each implementation is a serlializer, suggesting replacing interface abstract class?

after-afterthought: overridden methods can't static either, changing abstract class doesn't any.

from logical point of view these methods should static, because logically don't work on particular instance , don't use shared resources.this class don't have state well. but... pragmatic point of view, instant class brings many benefits, like:

  • class (interface) if testable,
  • follows oop , solid principles,
  • can registered singleton, can create 1 instance of object,
  • it's easy add dependencies these classes
  • easy maintain
  • some useful design patterns can applied (e.g. decorator, composite)
  • can lazy loaded , disposed in time

in case, in opinion, should hide implementation behind interface , register singleton, e.g.(using autofac)

builder.registertype<myxmlserializer>().as<idataserializer>().singleinstance(); 

in addition, if need to, can create extension method interface , add static methods contract.

more information can found here:


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -