策略模式與狀態模式

狀態模式

狀態模式將狀態的切換交由具體的處理節點做判斷, 容器只提供執行上下文

類模式實現

/**
 * 處理節點類
 */
abstract class State{
  state: string
  next: State
  
  constructor(state: string, next?: State){
    this.state = state
    this.next = next || this
  }
  // 狀態切換方法,交由具體的子類實現
  abstract change():State
}


/**
 * 狀態控制類
 */
class Store{
  // 游標, 標記下一可調用狀態
  currentState: State
  constructor(currentState: State){
    this.currentState = currentState
  }
  run(){
    // 修改當前游標指向
    this.currentState = this.currentState.change()    
  }
}


/**
 * 具體的狀態節點類實現
 */
class Success extends State{
  constructor(next?: State){
    const state = 'SUCCESS'
    super(state, next)
  }
  
  // 子類實現具體的狀態處理
  change(): State {
    console.log(this.state)
    return this.next    
  }
}


class Fail extends State{
  constructor(next?: State){
    const state = 'Fail'
    super(state, next)
  }
  
  change(): State {
    console.log(this.state)
    return this.next
  }
}


class Loading extends State{


  success: State
  fail: State


  constructor(success?: State, fail?: State){
    const state = 'Loading'
    super(state)
    this.success = success || this
    this.fail = fail || this
  }
  
  change(): State {
    console.log(`
      ---------- LOADING ----------
    `)
    this.next = Number.parseInt(`${Math.random() * 10}`) % 2 ? this.success : this.fail
    return this.next
  }
}


function stateMod(){
  const success = new Success()
  const fail = new Fail()
  const loading = new Loading()
  const store = new Store(loading)


  success.next = loading
  fail.next = loading
  loading.success = success
  loading.fail = fail
  
  for(let i = 0; i < 10; i++){
    store.run()
  }
}


stateMod()

策略模式

調用具體執行的函數的決策交由容器決定

類實現

// 決策容器
abstract class Strategy<T extends string>{
  state: T
  constructor(initState: T){
    this.state = initState
  }


  // 狀態的的切換交由的策略決策處理
  abstract strategy():void
}


type State = 'success' | 'fail' | 'loading'


class LoadData extends Strategy<State>{
  loading: Function
  success: Function
  fail: Function


  constructor(loading: Function, success: Function, fail: Function){
    super('loading')
    this.loading = loading
    this.success = success
    this.fail = fail
  }


  strategy(){
    switch (this.state) {
      case 'success':
        this.success()
        this.state = 'loading'
        break;
      case 'fail':
        this.fail()
        this.state = 'loading' 
        break;
      case 'loading':
       this.state = this.loading() ? 'success' : 'fail'
       break; 
    }
  }
}


function StrategyMod(){


  // 具體的執行不參與狀態的切換
  const success = () => console.log('Success')
  const fail = () => console.log('Fail')
  const loading = () => {
    console.log(`
    ---------- LOADING ----------
  `)
   return Number.parseInt(`${Math.random() * 10}`) % 2
  } 


  const loadData = new LoadData(
    loading,
    success,
    fail
  )


  for(let i = 0; i < 10; i++){
    loadData.strategy()
  }
}
StrategyMod()

函數方式

interface IStrategy<T>{
  (s: T): T
}


type State = 'success' | 'fail' | 'loading'


/**
 * 值容器
 */
class Container<T>{
  state: T
  constructor(state: T){
    this.state = state
  }


  of(s: T){
    return new Container(s)
  }


  map(cb:IStrategy<T>){
    return this.of(cb(this.state))
  }
}


type Warp<T extends string> = (s: T) => Warp<T> 


function StrategyMod(){


  // 具體的執行不參與狀態的切換
  const success = () => console.log('Success')
  const fail = () => console.log('Fail')
  const loading = () => {
    console.log(`
    ---------- LOADING ----------
  `)
   return Number.parseInt(`${Math.random() * 10}`) % 2
  } 


  // 決策函數
  const loadData = function(s: State): State{
    switch (s) {
      case 'success':
        success()
        return 'loading' 
      case 'fail':
        fail()
        return 'loading' 
      case 'loading':
        return loading() ? 'success' : 'fail' 
    }
}


  const list = new Array(10).fill('')
  list.reduce<Container<State>>((acc) => acc.map(loadData), new Container<State>('success'))
}


StrategyMod()

總結

策略模式與狀態模式,關注的是狀態切換的控制權。

  • 策略模式由中心容器根據輸入控制具體的執行函數,控制權在容器中
  • 狀態模式由當前的執行節點控制具體的狀態設置, 控制權在狀態節點中

策略模式更中心化,狀態模式更分布式。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容