先说下状态机 :
意图:允许一个对象在其状态改变时,改变它的行为。看起来对象似乎修改了它的类。
适用性:
1、一个对象的行为取决于它的状态,并且它必须在运行过程中可以根据它的状态改变它的行为;
2、一个操作中含有庞大的多分支的条件语句,并且这些分支依赖于该对象的状态;这个状态通常使用一个或多个枚举常量表示;通常,有多个操作包含这一相同的条件结构;State模式把每一个条件分支放入一个独立的类中;这使得你可以根据对象自身的情况把对象的状态作为一个对象,而且这一对象可以不依赖于其它对象而独立变化;
-
示例如下
- 简单来说 你的对象的行为取决于state 就可以算是状态机 ,比如我们APP中实现的promise 也是一种状态机,
[QXPromise promise:^(ResolveHandler resolve, RejectHandler reject) {
// bill_id=&user_id=
[[MXNetTool defaultManager] getWithParams:@{@"bill_id":model.model.bill_id,@"user_id":[AppSetting appsetting].userid} url:Biztask_cancelbill success:^(NSURLSessionDataTask *task, id responseObject) {
resolve(responseObject[responseObject]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
reject(error);
}];
}].then(^id(id data){
if ([data[@"data"] isEqualToString:CODE200]) {
[self showMXHint:@"取消账单成功" yOffset:0];
}
return nil;
})
.catch(^id(NSError *e){
[self showHint:e];
}).finally(^(){
});
- 废话少说 我们看下实现一个swift状态机
stateMachine
event
state
将会实现这三个类。
event 会绑定事件,有原始状态至目标状态。
state绑定每个状态进入或退出的事件。
statemachine 会操作event。
event 代码
open class Event<T:Hashable> : Equatable {
open let name : String
open let sourceValues:[T]
open let destinationValue:T
open var shouldFireEvent:((_ event:Event)->Bool)?
open var willFireEvent:((_ event:Event)->Void)?
open var didFireEvent:((_ event:Event)->Void)?
required public init(name:String,sourceValues sources:[T],destinationValue destination:T){
self.name = name
self.sourceValues = sources
self.destinationValue = destination
}
static open func == (lhs:Event<T>,rhs:Event<T>)->Bool{
return lhs.name == rhs.name
}
}
看到 event绑定了事件以及状态。
state
open class State<T:Hashable> {
public typealias enterStateHandle = ((_ enteringState:State<T>)->Void)
open let value:T
open var willEnterState:enterStateHandle?
open var didEnterState:enterStateHandle?
open var willExitState: enterStateHandle?
open var didExitState: enterStateHandle?
public init(_ value:T){
self.value = value
}
}
同样 state也会绑定事件 以及值 该值为你的几种状态。一般可以为枚举。
现在就差状态机了
open class StateMachine<T:Hashable> {
var initialState:State<T>
open private(set) var currentState:State<T>
private lazy var availableStates:[State<T>] = []
private lazy var events : [Event<T>] = []
required public init(initialState:State<T>){
self.initialState = initialState;
self.currentState = initialState;
availableStates.append(initialState)
}
open func activateState(_ stateValue:T) {
if (isStateAvailable(stateValue)){
let oldState = currentState
let newState = stateWithValue(stateValue)!
newState.willEnterState?(newState)
oldState.willExitState?(oldState)
currentState = newState
oldState.didExitState?(oldState)
newState.didEnterState?(newState)
}
@discardableResult
open func fireEvent(_ event:Event<T>) -> Transition<T> {
return _fireEventNamed(event.name)
}
@discardableResult
open func fireEvent(_ eventName:String) ->Transition<T> {
return _fireEventNamed(eventName)
}
}
private extension StateMachine {
func _fireEventNamed(_ eventName:String)->Transition<T> {
if let event = eventWithName(eventName) {
let possibleTransition = possibleTransitionForEvent(event)
switch possibleTransition {
case .success(sourceState: let sourceState, destinationState: let destinationState):
if let shouldBlock = event.shouldFireEvent {
if shouldBlock(event) {
event.willFireEvent?(event)
activateState(event.destinationValue)
event.didFireEvent?(event)
return Transition.success(sourceState: sourceState, destinationState: destinationState)
} else {
return Transition.error(.transitionDeclined)
}
}
else {
let sourceState = self.currentState
event.willFireEvent?(event)
activateState(event.destinationValue)
event.didFireEvent?(event)
return Transition.success(sourceState: sourceState, destinationState: destinationState)
}
default:
return possibleTransition
}
} else {
return Transition.error(.unknownEvent)
}
}
}
}
下面就不贴代码了。
statemachine 绑定了事件以及 状态。若需要改变状态,只需要调用 fireEvenet即可
如若调用成功将会触发state以及event绑定的事件。
以下为测试代码
var machine: StateMachine<String>!
let state = State("Initial")
state.willExitState = { _ in
print("fuck 1")
}
state.willEnterState = { _ in
print("fuck 2")
}
state.didEnterState = { _ in
print("fuck 3")
}
state.didExitState = { _ in
print("fuck 4")
}
let passedState = State("Passed")
passedState.willExitState = { _ in
print("fuck pass 1")
}
passedState.willEnterState = { _ in
print("fuck pass 2")
}
passedState.didEnterState = { _ in
print("fuck pass 3")
}
passedState.didExitState = { _ in
print("fuck pass 4")
}
machine = StateMachine(initialState: state)
machine.addState(passedState)
let event = Event(name: "Pass", sourceValues: ["Initial"], destinationValue: "Passed")
_ = try? machine.addEvent(event)
let transition = machine.fireEvent("Pass")
let event2 = Event(name: "Pass3", sourceValues: ["Passed"], destinationValue: "Initial")
_ = try? machine.addEvent(event2)
let transition2 = machine.fireEvent("Pass3")
执行结果为
fuck pass 2
fuck 1
fuck 4
fuck pass 3
fuck 2
fuck pass 1
fuck pass 4
fuck 3
此状态机还是比较好理解的。虽然我们用枚举也能很方便的知道状态变化。但是这种做法更加抽象。并且代码也是漂亮的。
网友评论