状态模式中类有状态,状态的修改会改变整个类行为。策略模式没有状态,策略的选择由客户端决定。具体的说,在客户端,可以通过给策略接口不同的实现类达到算法/业务的切换。而状态模式下,通过修改对象状态来切换算法/业务。看起来似乎也没差,但最明显的区别是,在状态模式中,对象可以在某些情况下切换自己的状态。
- 策略模式
Class RichPerson {
eat (food) {
console.log(food.taste())
}
}
Class Fish {
taste () {
retrun '味道不错'
}
}
Class Earth {
taste () {
retrun '难以下咽'
}
}
Class Water {
taste () {
retrun '没啥味道但能解渴'
}
}
let me = new RichPerson()
me.eat(new Fish())
me.eat(new Earth)
me.eat(new Wather)
有钱可以任意选择想要吃的东西!
- 状态模式
Class You {
constructor () {
this.food = null
}
changeFood (newFood) {
this.food = newFood
}
eat (food) {
console.log(food.taste())
}
}
Class Water {
taste () {
retrun '白开水毫无味道'
}
}
Class Earth {
taste () {
retrun '只能填肚子'
}
}
let you = new You()
you.changeFood(new Fish())
you.eat()
you.changeFood(new Earth())
you.eat()
没钱只能在有限的选择里进行选择
- 总结
策略模式有钱任性选择更多拓展性更强,状态模式选择固定封装度更高更加内敛。
网友评论