决定使一个类静态

时间:2012-11-17 01:41:30

标签: java design-patterns static

我有一个服务器项目,我已分成6个不同的类:

  • ServerConnectionManager - 类是所有其他类的中心
  • 连接 - 只要客户端连接并启动线程
  • ,就会创建此对象
  • ServerListner - 这是侦听用户输入的Thread类
  • ServerSender - 这是向一个或多个用户发送消息的类
  • ServerInformation - 此类包含两个聊天人员列表和一个连接,此类还允许您搜索列表以查找specefic人员和/或连接
  • ChatPerson - 此对象包含连接到服务器的每个人的用户名

正如您现在已经猜到的那样,这是一个聊天程序的服务器!

我的问题是:

我想在此项目中使用Design patteren(Mediator),因此ServerConnectionManager包含每个类使用的所有关键方法。例如,在ServerInformation类中添加连接到连接列表。

但是,因为ServerInformation类不能被称为对象,因为它只有很多方法(函数),除了存储和搜索数据之外没有其他真正的目的,将它设置为静态是个好主意吗?或者我应该坚持计划,让一切都通过ServerConnectionManager?

以下是我的代码示例:

ServerConnectionManager

public class ServerConnectionManager {

    private static ServerSocket server;
    private static Socket connection;
    private static ServerInformation ai = new ServerInformation();
    private static boolean connected = false;
    private static final int portNumber = 7070;
    private static int backLog = 100;

    /**
     * This method launches the server (and the application)!
     * @param args
     */
    public static void main(String[] args){
        startServer();
        waitForConnection();
    }


    /**
     *This method sets the serverSocket to portNumber and also adds the backLog.
     */
    private static void startServer() {
        try {
            server = new ServerSocket(portNumber, backLog);
            connected = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * This method waits for a connection aslong as the serverSocket is connected.
     * When a new client connects it creates an Object of the connection and starts the individual procedure.
     */
    private static void waitForConnection() {
        while (connected) {
            try {
                connection = server.accept();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Connection c = new Connection(connection);
            addConnection(c);
            waitForConnection();
        }

    }


    public static void closeMe(Socket con) {
        for (Connection conn : ai.getConnectionList()) {
            if (conn.getConnection() == con) {
                ai.getList().remove(ai.getList().indexOf(ai.getChatPersonByConnection(con)));
                ai.getConnectionList().remove(conn);

                System.out.println(ai.getList());
                System.out.println(ai.getConnectionList());
                conn.close();
                break;

            }
        }

    }
    public static void addConnection(Connection con){
        ai.addToConnectionList(con);

    }
    public static void addChatPerson(ChatPerson p){
        ai.add(p);
        System.out.println(ai.getList());
    }



}

连接

public class Connection{
    private Socket connection;
    public Connection(Socket connection){
        this.connection = connection;
        ServerListner cl = new ServerListner(Connection.this);
        cl.start();
    }
    public Socket getConnection(){
        return this.connection;
    }
    public void close() {
        try {
            connection.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


}

ServerListner

public class ServerListner extends Thread {

    private Socket connection;
    private BufferedReader br;
    private ChatPerson person;
    private Connection con;
    private ServerInformation ai = new ServerInformation();
    private ServerSender sender = new ServerSender();

    public ServerListner(Connection con){
        this.con = con;
        connection = con.getConnection();
        try {
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public Socket getConnection(){
        return this.connection;
    }
    public void run(){
        System.out.println(con.getConnection().isConnected());
            try {
                String inString;
                while ((inString = br.readLine()) != null) {
                    if (inString.equalsIgnoreCase("Disconnect")) {
                        System.out.println(inString);
                        break;
                    }else {
                        processInput(inString);
                    }
                }
                ServerConnectionManager.closeMe(connection);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    public void processInput(String input){
        if (input.equalsIgnoreCase("Connect")) {
            sender.sendMessageToConnection(this.connection, "Accepted");
        }
        if (input.equalsIgnoreCase("UserInformation")) {
            try {
                String username = br.readLine();
                person = new ChatPerson(username, connection);
                ServerConnectionManager.addChatPerson(person);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (input.equalsIgnoreCase("SearchByCon")) {
            String name = ai.searchByConnection(connection);
            System.out.println(name);
        }

    }
}

ServerSender

public class ServerSender {
    private PrintWriter pw;
    private ServerInformation ai = new ServerInformation();

    public void addToList(){

    }
    public void sendToAll(String message){
        for (Connection c : ai.getConnectionList()) {
            try {
                pw = new PrintWriter(c.getConnection().getOutputStream());
                pw.print(message);
                pw.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
    /** 
     *
     * @param con
     * @param message
     */

    /*
     * Note - Denne metode gør også at jeg kan hviske til folk!:)
     */
    public void sendMessageToConnection(Socket con, String message){
        try {
            PrintWriter print = new PrintWriter(con.getOutputStream());
            print.println(message);
            print.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}

ServerInformation

public class ServerInformation{
    private ArrayList<Connection> connectedClients = new ArrayList<Connection>();
    private ArrayList<ChatPerson> list = new ArrayList<ChatPerson>();


    public ArrayList<Connection> getConnectionList(){
        return connectedClients;
    }
    public void addToConnectionList(Connection con){
        connectedClients.add(con);
    }
    public String searchByConnection(Socket myConnection){
        for (ChatPerson p : list) {
            if (p.getConnection() == myConnection) {
                return p.getName();
            }   
        }
        /*
         * If none found!
         */
        return null;
    }

    public ChatPerson getChatPersonByConnection(Socket myConnection){
        for (ChatPerson p : list) {
            if (p.getConnection() == myConnection) {
                return p;
            }
        }
        return null;
    }

    public void add(ChatPerson p){
        list.add(p);
    }

    public void removeByName(String name){
        for (ChatPerson p : list) {
            if (p.getName().equalsIgnoreCase(name)) {
                list.remove(p);     
            }
        }
    }
    public String searchList(String name){
        for (ChatPerson p : list) {
            if (p.getName().equalsIgnoreCase(name)) {
                return p.getName();
            }
        }
        return null;
    }   
    public ArrayList<ChatPerson>getList(){
        return list;
    }

}

ChatPerson

public class ChatPerson {
    private String chatName;
    private Socket connection;

    /*
     * This is for furture development
     * private Integer adminLevel;
     */

    public ChatPerson(String name, Socket connection){
        this.chatName = name;
        this.connection = connection;
    }
    public void setName(String name){
        this.chatName = name;

    }
    public String getName(){
        return chatName;

    }
    public String toString(){
        return "Username: "+chatName;
    }
    public Socket getConnection(){
        return connection;
    }
}

提前谢谢你,顺便说一下,因为我是一名学生,如果你有时间对我的代码进行评分并且提出如何改进的建议(如果有的话)会很好。

1 个答案:

答案 0 :(得分:2)

你可能意味着只有静态方法的类,而不是静态类。静态内部类是不同的(你可以谷歌)。

在您的经理中使用非静态方法的优点:

  • 您可以在测试过程中使用像Mockito这样的框架轻松模拟它们。
  • 您可以在重构代码时将它们拉到某个界面。
  • 使用静态方法不是面向对象的编程,因为这样的方法调用与类的任何实例(对象)都没有关联。