在制造環境中,對于特定流程,有相當簡單的 C# Winforms 桌面應用程式涉及在無限回圈上運行的基于列舉的狀態機,其結構類似于以下(為了示例,狀態名稱保持通用)。
switch(state):
case STATE0:
// code (ui update, business logic, and/or database/device communication)
if (...)
state = STATE1; // goes to next state
break;
case STATE1:
// code (ui update, business logic, and/or database/device communication)
if(...)
state = STATE2; // goes to next state
break;
case STATE2:
// code (ui update, business logic, and/or database/device communication)
if(...)
state = STATE1; // goes back to STATE1
else if (...)
state = STATE3; // goes to next state
break;
case STATE3:
// code (ui update, business logic, and/or database/device communication)
if (...)
state = STATE0; // goes back to STATE0
break;
有許多產品經歷了這個程序。跨產品的許多狀態幾乎完全相同(例如 state0)。但是州內的產品特定邏輯在不同產品之間略有不同。
有沒有辦法將上述 switch 陳述句重構為更干凈、更靈活的有限狀態機,可以解釋狀態內的變化?
uj5u.com熱心網友回復:
如果你有多個狀態并且需要根據狀態改變行為,那么我們可以使用策略模式結合工廠模式。
首先,我們需要宣告狀態:
public enum State
{
State_1,
State_2,
State_3,
State_4
}
然后根據狀態我們需要選擇一些行為。我們可以把行為放在課堂上。我們稱之為產品。所以我們需要創建一些抽象類,并將所有重復的邏輯放在這個抽象類中。然后如果某些類的行為不同或者我們想添加新的行為,那么我們將創建派生類。通過添加新類,我們保持開放封閉原則。
public abstract class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
public string TheSameBehaviorForAllProducts()
{
return "TheSameHehaviorForAllProducts";
}
public virtual string BehaviorThatCanBeOverridenInDerivedClasses()
{
return "TheSameHehaviorForAllProducts";
}
}
和派生類Product:
public class Product_A : Product
{
public override string BehaviorThatCanBeOverridenInDerivedClasses()
{
return "New Behavior Here";
}
}
public class Product_B : Product
{
public override string BehaviorThatCanBeOverridenInDerivedClasses()
{
return "New Behavior Here";
}
}
public class Product_C : Product
{
public override string BehaviorThatCanBeOverridenInDerivedClasses()
{
return "New Behavior Here";
}
}
然后我們可以創建一個類似 mapper 的東西,它映射State到Product. 它也可以被認為是工廠模式:
public class StateToProduct
{
public Dictionary<State, Product> ProductByState = new()
{
{ State.A, new Product_A() },
{ State.B, new Product_B() },
{ State.C, new Product_C() }
};
}
和我們的狀態機:
public class StateMachine
{
// Here your logic to get state
public State GetState()
{
return State.A;
}
}
然后我們可以像這樣運行大系統:
public class SomeBigSystem
{
public void Run()
{
StateMachine stateMachine = new();
StateToProduct stateToProduct = new();
Product product = stateToProduct.ProductByState[stateMachine.GetState()];
// executing some business logic
product.BehaviorThatCanBeOverridenInDerivedClasses();
}
}
So we've created simple classes that are testable and we used here Strategy pattern.
I highly recommend you to read about SOLID and techniques of refactoring
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450764.html
