简体   繁体   中英

Enforce static method for use in a factory

I am creating a factory which uses a delegate to call a static method on each registred type in order to create an instance of the type.

In the factory I have the delegate definition:

public delegate GridColumnBase ColumnFactoryMethod();

and I would like each type inheriting from GridColumnBase to implement a static CreateInstance() method. I can't make CreateInstance a static abstract member of GridColumnBase , so how do I enforce that each class implement this method?

Edit: Thinking about this a little more I reached a conclution that CreateInstance() is not a feature of a class inhereting GridColumnBase , but is a feature of a class wanting to be included in the factory. Maybe I don't need to enforce this on the base class level. Maybe I need to leave it to the implementing class to decide how it whishes to participate in the factory process, ie passing in to the factory any function it whishes to delegate. Does this make sense to anyone but me? :)

You could create another interface that each class implements to force a static factory method. Is each type going to use the same or similar factory methods?

I ended up opting for a smart use of reflection. To give credit where credit is due, I modified this solution http://www.matlus.com/high-performance-class-factory/ for my own needs.

I think it's a nice and elegant solution to the problem, and comparing results of our profiler, it does not degrade performance much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM