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並將它傳遞給主類。現在只會創建一個對象,用戶可以整天點擊連接/斷開連接。
在這裏進行的最佳途徑是什麼?
- 存放在主類
- 存放在主類
- 類對象的服務器對象依賴
- 兩者都是不好的想法(如果是這樣,爲什麼?我該怎麼辦呢?)