开发者

How to improve polymorphism with design patterns

I'm attempting to design a system that will allow the processing of multiple types of file. The idea being that there's a single applicati开发者_开发技巧on to handle the actual manipulation of the files on disk, while developers can write custom libraries that will be able to do whatever they want with the files once loaded.

I current have a structure that looks like this:

Original Image

How to improve polymorphism with design patterns

Where the application publishes an IClient interface that the custom written libraries are free to implement. Client1 to Client3 would each have a different implementation and respond to each type of file in a different way.

The Populate method on File is overriden in the derived classes to call the correct PopulateFrom method on the IClient interface, passing in the calling file.

Therefore the PopulateFrom method on the class implementing IClient is passed a file of a specific type so that it has to access the underlying data (CSVDataReader or XDocument in this example) to parse into whatever domain-specific objects it wants.

Using this design for every new type of file I add to the system I would have to add a new method to IClient which isn't ideal. To preserve compatibility with the client classes that don't have the method accepting the new file type I'm going to have to create a new interface that specifically supports that type and have the new client implement that:

Original Image

How to improve polymorphism with design patterns

That all works, but I was wondering whether there's a better way of supporting the multiple file types without having to add a new interface every time, possibly using a design pattern?


Here is an option: your PopulateFrom method should not take a specific file type, instead it should take a FileStream or MemoryStream, after all a file is simply a stream of bytes, it is the organisation of those bytes that makes each file type unique.

Additionally, you may want to implement a method similar to this:

bool CanProcess(FileStream myFile)

that way you can query each provider in a generic way and it will tell you if it can process that particular file. Doing it this way will allow you to implement more file types and more providers without having to extend your interface or mess with the existing providers.

Check out the Provider pattern to see if it helps.


Your design violates the design principle known as Dependency inversion, because clients depend on concrete classes instead of abstract ones.

You should reconsider implementing your clients in a way they work with the abstract type (Application::File). If there's absolutely no way to do that, then you should redesign the class hierarchy.

Think about it. If an abstraction is seldom used then it is probably useless. Robert Martin terms this as the Stable abstractions principle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜