In my program, I upload one file in several servers, like google drive, dropbox and so on at the same time. I'm using the adapter design pattern to adapt each server api, so each server concrete class implements a FileServer interface, and in the end I have a list of FileServer objects. My question: as my program will have to support new servers in the future, what is the best way to encapsulate all that server objects instantiation (I mean, the "...= new..." part)? What comes in mind is factory pattern, but is it correct to return a list in the factory method? Thank you.

有帮助吗?

解决方案

Usually the factory pattern encapsulates the complexity behind creating single object from some sort of "materials", like specification. For example, given a URL, create a connection to the server defined by a URL.

In your case, the canonical Factory pattern would take some specification for the file store (URL, context object, etc.) and create a single file server object. While there's nothing forbidding you from returning a list of objects from a factory method given a list of specifications, it's almost as easy and arguably cleaner to iterate over the list of specs and call the factory method for each one. Something like this:

List<FileServer> fsList = new ArrayList<FileServer>();
for(FSSpec spec : fileServerSpecs)
{
    FileServer fs = FileServerFactory.create(spec);
    fsList.add(fs);
}

// do something with your list of file servers.

This is also more reusable because there are likely situations where you want to create a single file server from a specification without the bother of creating a single-item list with just that specification to pass to your factory method.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top