0
我在做一个包括自定义OPC客户端的项目。 The Class Main表示WPF应用程序中的MainWindow。 私人领域_opcServer
将持有一个对象供进一步使用。 任何时候只允许有一个_opcServer
对象。 我想出了这个(这是所有的示例代码和正常工作)的代码全局“类对象”或全局“服务器对象”
// "Main" Class --> it's a WPF Window
public class Main
{
// the "global" server object
private OpcServer _opcServer = new OpcServer();
public Main() {}
private void connectOpcServer()
{
if(this._opcServer == null)
{
// the "global" server object
this._opcServer = this.opcClientFactory().connectOpcServer("someOpcServer");
if(this._opcServer != null)
{
// we made the connection
}
else
{
// connection failed
}
}
}
private void disconnectOpcServer()
{
if(this._opcServer != null)
{
if(this.opcClientFactory().disconnectOpcServer(this._opcServer))
{
// disconnected
this._opcServer = null;
}
else
{
// something went wrong
}
}
}
private OpcClient ocpClientFactory()
{
OpcClient opcClient = new opcClient();
return opcClient;
}
}
// Client Class
public class OpcClient
{
// the server object
private OpcServer _opcServer = new OpcServer();
public OpcClient() {}
public OpcServer connectOpcServer(string progID)
{
bool madeConnection = this._opcServer.Connect(progID);
if(madeConnection)
{
return this._opcServer;
}
else
{
return null;
}
}
public bool disconnectOpcServer(OpcServer opcServer)
{
this._opcServer = opcServer;
if(this._opcServer.disconnect())
{
this._opcServer = null;
return true;
}
return false;
}
}
没有太多的评论,但我想你明白了吧。 每次通过用户操作触发连接或断开连接时,都会创建一个OPC客户端的新对象,并且服务器对象将在一个或另一个方向上传递。 这样会有更多的方法(如读取标签等),但由于用户每天只能使用它们一次或两次,所以我发现在创建新对象和传递它们之间没有问题。
但是,如果有一个真正的有趣的用户认为他必须一直使用这些东西(连接/断开连接等)。然后我会最终创造出许多物品!
我给了它一个想法,并提出了这一点。
public class Main
{
// the client object
private OpcClient _opcClient = OpcClient.Instance;
public Main(){}
private void connectOpcServer()
{
if(this._opcClient.connectOpcServer("someOpcServer"))
{
// we made the connection and can now use
// this._opcClient.opcServer
}
else
{
// connection failed
}
}
private void disconnectOpcServer()
{
if(this._opcClient.disconnect())
{
// disconnected
}
else
{
// something went wrong
}
}
}
public class OpcClient
{
private static OpcClient _instance;
public static OpcClient Instance
{
get
{
if(instance == null)
{
_instance = new OpcClient();
}
return _instance;
}
}
private OpcClient()
{
this.opcServer = new OpcServer();
}
public OpcServer opcServer
{
get;
private set;
}
public bool connectOpcServer(string progID)
{
return this.opcServer.Connect(progID);
}
public bool disconnectOpcServer()
{
return this.opcServer.disconnect();
}
}
现在我创建一个OPC客户端的singelton并将它传递给主类。现在只会创建一个对象,用户可以整天点击连接/断开连接。
在这里进行的最佳途径是什么?
- 存放在主类
- 存放在主类
- 类对象的服务器对象依赖
- 两者都是不好的想法(如果是这样,为什么?我该怎么办呢?)