我需要帮助重构以下类,
以下是在 switch 中具有多种操作的类操作:我想避免使用 switch 语句。我读了几篇关于使用多态性和状态模式的文章。但是当我重构类时,我无法访问许多变量,属性
我是否对是否将操作用作抽象类或实现接口。
只是想知道哪种类型的重构在这种情况下会帮助
多态性或状态模式?
以及何时使用它们?
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);