问题描述
我已经在 Java 中为我的套接字库实现了状态模式。 我简化了代码以减小大小并提高可读性只是为了演示问题。 我不知道如何通过状态类来封装 Socket 类的使用。 我写了评论以更好地理解问题。 所以,有一个示例代码:
package com.test;
enum ConnectionAttemptResult {
ConnectionAttemptStarted,AlreadyInProgress,AlreadyConnected,UnableToCreateSocket,UnableToConnectSocket,UnableToCreateReadEvent
}
class SocketAddress {
static SocketAddress LocalhostPort(int port) {
// Code removed.
return new SocketAddress();
}
}
class Socket {
private State currentState;
Socket() {
this.currentState = new NotActiveState(this);
}
public ConnectionAttemptResult Connect(SocketAddress remoteAddress) {
return this.currentState.Connect(remoteAddress);
}
// Socket class is external and will be used by user.
// So further methods must be private because they are internal.
// Calling these methods by a user may broke class functionality.
// But I can't make them private because then states couldn't access them.
public void SwitchState(State newState) {
this.currentState = newState;
}
// I removed a lot of code of this class to simplify the code.
public boolean CreateSocket() {
// Code removed.
return true;
}
public boolean ConnectSocket(SocketAddress remoteAddress) {
// Code removed.
return true;
}
public boolean CreateReadEvent() {
// Code removed.
return true;
}
}
abstract class State {
protected Socket socket;
State(Socket socket) {
this.socket = socket;
}
public abstract ConnectionAttemptResult Connect(SocketAddress remoteAddress);
}
class NotActiveState extends State {
NotActiveState(Socket socket) {
super(socket);
}
@Override
public ConnectionAttemptResult Connect(SocketAddress remoteAddress) {
if (!socket.CreateSocket())
return ConnectionAttemptResult.UnableToCreateSocket;
if (!socket.ConnectSocket(remoteAddress))
return ConnectionAttemptResult.UnableToConnectSocket;
if (!socket.CreateReadEvent())
return ConnectionAttemptResult.UnableToCreateReadEvent;
socket.SwitchState(new ConnectingState(socket));
return ConnectionAttemptResult.ConnectionAttemptStarted;
}
}
class ConnectingState extends State {
ConnectingState(Socket socket) {
super(socket);
}
@Override
public ConnectionAttemptResult Connect(SocketAddress remoteAddress) {
return ConnectionAttemptResult.AlreadyInProgress;
}
}
class ConnectedState extends State {
ConnectedState(Socket socket) {
super(socket);
}
@Override
public ConnectionAttemptResult Connect(SocketAddress remoteAddress) {
return ConnectionAttemptResult.AlreadyConnected;
}
}
class Main {
public static void main(String[] args) {
Socket socket = new Socket();
socket.Connect(SocketAddress.LocalhostPort(9898));
// But I also can call internal methods and break the class functionality,because now they are public.
socket.CreateSocket();
socket.CreateReadEvent();
}
}
我的错误在哪里? 开发人员通常如何实现这种模式保存封装? 希望得到您的帮助! 提前致谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)