The ideal pattern

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • enigmagame
    New Member
    • Apr 2010
    • 1

    The ideal pattern

    In a software that I'm developing, I've a problem, I'm searching a solution for that, and I think that a solution can come from a design pattern, so I'm here for some suggestions.
    The software must connect to a server, the server can be of a different type (for example FTP and SQL), after the connection the software must perform some actions, for example download a list of something.
    We have different type of server, so if the software is connected on a FTP server, the action is download a list of files, if the software is connected on a SQL server the action is a query on a table.
    When the software starts, it loads a configuration file, on this file there are some server informations, what happen in reality is a population of a list of ServerInfo objects, each object contains the server type, the address and the login data.
    I'm searching an elegant and transparent solution, I don't want code like this:
    Code:
    Server server; 
    
    if (serverInfo.type == FTP) 
        server = new FTPServer(); 
    else if (serverInfo.type == SQL) 
        server = new SQLServer(); 
    
    server.connect();
    Studying the problem I've found a possible solution with the Abstract Factory pattern, but I'm really new to the world of desing patterns, so I'm not sure if this is the correct solution, and I don't understand very well how to model my problem on this pattern.
    Thanks.
  • jhumelsine
    New Member
    • May 2010
    • 9

    #2
    Use Factory Method

    Use Factory Method for this. You'll still have the if/else in your code, but it will be in a better spot.

    Create a static method in Server called create. It will look something like the following:
    Code:
    public static Server create(ServerInfo info)
    {[INDENT]if (info == FTP)[INDENT]return new FTPServer;[/INDENT]
    else if (info == SQL)[INDENT]return new SQLServer;[/INDENT][/INDENT]
    }
    Your implementation becomes:

    Code:
    Server server = Server.create(serverInfo.type);
    
    server.connect;
    Last edited by Frinavale; May 5 '10, 08:57 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

    Comment

    Working...