gpt4 book ai didi

algorithm - 策略和状态设计模式之间的区别,一个状态如何知道它的前任?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:57 24 4
gpt4 key购买 nike

我在 refactoring.guru 中阅读了状态和策略设计模式网页中的网站 StateStrategy .作者说

This structure may look similar to the Strategy pattern, but there’s one key difference. In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other.

作者还说,ConcereteState 类,存储一个变量 context,它是 Context 类的对象,通过这个变量,状态可能互相认识。

有两件事我不明白:

  1. 一个国家如何了解其前身?
  2. 我应该在哪里实现状态之间的转换逻辑?例如 state1 通过输入 a 移动到 state2 并且通过 b 移动到 state4 ,这个逻辑到底应该在哪里实现?

这是我用php语言实现的策略的简单实现

<?php
class Algorithms{
public $algorithm;
function __construct(AlgorithmsInterface $algorithm){
$this->algorithm = $algorithm;
}

public function run(){
$this->algorithm->run();
}
}

interface AlgorithmsInterface{
public function run();
}

class Algorithm1 implements AlgorithmsInterface{
public function run(){
print "Algorithm1";
}
}

class Algorithm2 implements AlgorithmsInterface{
public function run(){
print "Algorithm2";
}
}


$payment = new Algorithms(new Algorithm2());
$payment->run();

这是我实现的状态设计模式的简单实现

<?php
interface State{
public function execute();
}

class Context{

public $state;

public function __construct(State $initialState){
$this->state = $initialState;
}

public function changeState(State $state){
$this->state = $state;
}

public function execute(){
$this->state->execute();
}
}

class State1 implements State{
public function execute(){
print "This is State1";
}
}

class State2 implements State{
public function execute(){
print "This is State2";
}
}

$initialState = new State1();
$state2 = new State2();
$context = new Context($initialState);
$context->execute();
$context->changeState($state2);
$context->execute();

?>

我看不出状态和策略之间有什么区别虽然我确切地知道这些策略的意图是什么。除此之外,代码中遗漏了状态之间的移动逻辑以及状态应了解其父级的方式。

最佳答案

从您的示例来看,这两种模式看起来非常相似。但是您的状态设计模式示例并不是真正的状态设计模式,因为您是从外部设置状态的。典型的状态设计模式在内部更改状态,并且经常将更改委托(delegate)给状态本身。让我们看一下简单的切换按钮。它有一个状态、按下它的方法和描述当前状态的方法(toString()):

class ToggleButton {
enum State {
ON {
public State press() {
return OFF;
}
},
OFF {
public State press() {
return ON;
}
};
abstract public State press();
}

State state = State.OFF;
public void press() {
state = state.press();
}
public String toString() {
return "Device is " + state;
}
}

所以从外部看,您没有设置状态,所以您不知道它处于哪种状态以及它会如何 react 。您使用:

button.press();
System.out.println(button);

所以关键的区别是,对于策略,你从外部传递策略,让你的对象执行一些操作(这不会改变策略),所以它是粘性委托(delegate)。

但是状态设计模式的目的是,状态应该改变,通常是内部改变,并且随着状态的改变,行为也会改变。因此,即使我们在计算某个任务之前设置了一些状态,它也可能会在任务完成期间在内部发生变化(通常会发生变化)。这是一种实现状态多态性的方法。另请注意,它通常与状态自动机相关。

关于algorithm - 策略和状态设计模式之间的区别,一个状态如何知道它的前任?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com