我需要幫助重構下面的類,如何避免長時間開關..need幫助重構
以下是與開關各種操作的一類操作: 我想避免statement.I閱讀幾篇文章的開關在使用多態性和狀態模式。但當我重構類我不能訪問許多變量,屬性
我困惑於是否使用操作作爲抽象類或實現一個接口。
只想知道哪種類型的重構將有助於在這種情況下
多態性或狀態模式?
何時使用它們?
public class Operation
{
public enum OperationType
{
add,
update,
delete,
retrieve
}
public enum OperationStatus
{
Success,
NotStarted,
Error,
Fail,
InProcess,
Free
}
// raise this event when operation completes
public delegate void OperationNotifier(Operation operation);
public event OperationNotifier OperationEvent=null;
private OperationStatus _status=OperationStatus.Free;
public OperationStatus Status
{
get { return _status; }
set { _status = value; }
}
private string _fileName = null;
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
private string _opnid = null;
public string OperationId
{
get { return _opnid; }
set { _opnid = value; }
}
private OperationType _type;
public OperationType Type
{
get { return _type; }
set { _type = value; }
}
public void performOperation(OperationType type, string parameters)
{
switch (type)
{
case OperationType.add:
_status = addOperation(parameters);
break;
case OperationType.update:
_status = updateOperation(parameters);
break;
case OperationType.delete:
_status = deleteOperation(parameters);
break;
case OperationType.retrieve:
_status = retrieveOperation(parameters);
break;
default:
break;
}
if (OperationEvent != null)
OperationEvent(this);
// return true;
}
public OperationStatus addOperation(string parameters)
{
DateTime start = DateTime.Now;
//Do SOMETHING BIG
TimeSpan timeTaken = DateTime.Now - start;
System.Diagnostics.Debug.WriteLine("addOperation:-" + _opnid + "-" + _fileName + "--" + timeTaken.Milliseconds);
return OperationStatus.Success;
}
...other operations here....
調用代碼類似於:
Operation oprnObj;
Operation.OperationType operationType;
oprnObj = new Operation();
oprnObj.FileName = String.Concat("myxmlfile",".xml");
oprnObj.OperationId = oprnid;
oprnObj.OperationEvent += new Operation.OperationNotifier(oprnObj_OperationEvent);
operation="add"; //get From Outside function getOperation()
operationType = (Operation.OperationType)Enum.Parse(typeof(Operation.OperationType), operation.ToLower(), true);
oprnObj.Type = operationType;
oprnObj.performOperation(operationType, parameters);
我目前使用.net 2.0嗎?我認爲擴展方法在3.0。 可以在2.0中做一些事情。 – Amitd 2009-12-23 13:09:04
您可以使用.Net 2.0的擴展方法。只要你使用C#3(你可以如果你有VS2008) – philsquared 2009-12-23 13:34:09
暫時仍然使用VS2005.但thx的信息:) – Amitd 2009-12-26 19:09:37