设计需要外部数据的独立类/框架
举个例子,我有一个名为 FileIdentifier
的类。此类:
- 具有识别方法,该方法接受
File
并返回表示该类型的String
。 - 需要外部数据,因为新的文件格式是可能的。
如何编写这个类,使其可以在任何项目中使用,同时保持不显眼?总的来说,在需要配置的独立框架中通常如何处理这方面的问题?
For the sake of an example, I have a class called FileIdentifier
. This class:
- Has the method identify which accepts a
File
and returns aString
representing the type. - Requires external data since new file formats are a possibility.
How could this class be written so it could used in any project while remaining unobstrusive? Overall, how is this aspect usually handled in standalone frameworks that require configuration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这完全取决于您如何识别文件类型。从你的问题来看,我认为这不是一个像解析文件扩展名那样简单的过程...
也就是说,也许你可以只使用外部 XML 文件、INI 或 db 表等来映射文件类型,并且只具有类读取该数据并返回任何内容...(您实际上希望使用一些类来保持整洁。)这样,只需更新外部数据并且类保持不变。
That all depends on how you identify the file type. From your question I would assume that it's not a process as trivial as parsing for the file extension...
That said maybe you could just use an external XML file, or INI, or db table etc. that maps file types and just have the class read that data and return whatever... (You would actually want to use a few classes to keep things clean.) That way only the external data would need to be updated and the class remain unchanged.
尝试使用责任链。
链中的每个实例都来自管理单个文件类型的不同类。文件在链中向下传递,一旦实例决定管理它,链就会停止并返回结果。
然后,您只需按照所需的顺序构建链(可能在顶部使用更常见的文件类型),提供管理框架中某些文件类型的默认类。这也应该很容易在您的应用程序中扩展,只需编写链的另一个子类来管理新的用户定义文件类型即可。
当然,链的基类(Handler,由 dofactory.com 调用)可以为其子类提供有用的受保护方法,以使它们的工作更容易。
Try with a chain of responsibility.
Each instance in the chain is from a different class that manages a single file type. The file is passed down in the chain, and as soon as an instance decides to manage it, the chain stops and the results are returned back.
Then you just would have to build the chain in the desired order (maybe with more common file types at the top), provide default classes that manages some file types in your framework. This shoud be also easy to extend in your applications, it's just a matter of writing another subclass of the chain that manages your new user-defined file types.
Of course your base class for the chain (the Handler, as called by dofactory.com) could provide useful protected methods to its subclasses in order to make their work easier.