Design pattern for creating object from file?
I am creating a software project in which most business objects are stored in files (in a legacy format). The objects will only be instantiated from an inputstream.
I do this today with making the constructor private and instantiating in a static function as follows:
public class BusinessObject {
private BusinessObject() {}
public static Busines开发者_C百科sObject fromStream(Stream stream) {
// Do initialization here
}
}
I would like my code to use established design patterns, since other people will be modifying it.
Is this a known pattern, or is there a design pattern that I can use instead of the above?
Thanks,
Martin
It looks you're making a Factory.
It might depend on what you're doing in the "initialization" phase, but you might be able to just make a constructor that takes in the Stream. If you're already disallowing the null constructor and only allowing them to be created from a Stream, it seems like the same only simpler. The only reason I can see this not working is if there are multiple subclasses of BusinessObject.
Sounds like you're looking for either deserialization or one of the construction patterns like factory
That's a very good way to do it. You're using the Factory pattern.
Ideally, you could use serialization/deserialization in your implementation to persist the object, but that may not be an option for you if the legacy format is required.
精彩评论