简体   繁体   中英

C# Class Interface Design

I'm trying to design a interface for iTextsharp (PDF creation library) that I'm using for my project. I don't want any reference to iTextsharp in my project, just the interface.

Lets say, I have

     interface IPdfTable { /* */ }
     public class PdfTable : IPdfTable  { /* */ }

     interface IPdfCell { /* */ }
     public class PdfCell : PdfCell { /* */ }

While I can easily build interfaces for each class individualy, I'm having difficulty on the implementation when these classes interact with each other. Somewhere in the code, I need tables to be able to accept an collection of cells.

The problem arrives when I have a have an collection of cells, and I need to add it to the table. Somehow I need to transform the IPdfCell into the original element that is accepted by the library (iTextSharp). I believe the quick and easy implementation was downcasting, but not a good design.

The only other solution I can think is using the interface to collection varies settings and create the orginal element (accepted by iTextsharp) on the fly when it is being passed around into other elements.

Is there a better implementation?

I don't understand the goal of such an interface. No matter what, your pdf generation code is going to be tied to the library you're using, building proxy classes/interfaces that exactly mirror the library doesn't prevent that, it just adds another layer. If you were to switch to a different PDF generation library, it is extremely unlikely that the new library would match up 1:1 with equivalents in iText, and you'd end up changing the interface and calling code anyway.

My recommendation would be to create an IPDFGenerator , and then create an iTextPDFGenerator:IPDFGenerator which IS coupled to iText, and leave it at that. You'll have the separation you want, the ability to keep iText out of your core services, but it won't require a bunch of pointless mapping between identical classes.

I think you should reevaluate the S, I, and D in SOLID and make sure you're not over-doing it.

Typically, you would have a translation layer that translates your interface facade implementation into the types supported natively by iTextSharp.

AutoMapper can help for this if you require property to property mappings and can remove a lot of the translation legwork for you.

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