前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >策略模式与状态模式

策略模式与状态模式

作者头像
copy_left
发布2022-03-23 14:11:05
1970
发布2022-03-23 14:11:05
举报
文章被收录于专栏:方球方球

状态模式

状态模式将状态的切换交由具体的处理节点做判断, 容器只提供执行上下文

类模式实现

代码语言:javascript
复制
/**
 * 处理节点类
 */
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()

策略模式

调用具体执行的函数的决策交由容器决定

类实现

代码语言:javascript
复制
// 决策容器
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()

函数方式

代码语言:javascript
复制
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()

总结

策略模式与状态模式,关注的是状态切换的控制权。

  • 策略模式由中心容器根据输入控制具体的执行函数,控制权在容器中
  • 状态模式由当前的执行节点控制具体的状态设置, 控制权在状态节点中

策略模式更中心化,状态模式更分布式。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022.03.05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 状态模式
    • 类模式实现
    • 策略模式
      • 类实现
        • 函数方式
        • 总结
        相关产品与服务
        容器服务
        腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档