【问题标题】:Any way to avoid Object/casts in the child classes here?有什么方法可以在这里避免子类中的对象/强制转换?
【发布时间】:2016-04-18 05:22:00
【问题描述】:

按照“人工智能 - 一种现代方法”一书,我正在尝试制作可以处理不同问题(从 A 到 B 的路径、滑块拼图等)的搜索算法实现(DFS、A* 等) .) 而不仅仅是一个特定的问题。

public abstract class Problem
{
    protected Problem(object initialState)
    {
        InitialState = initialState;
    }

    public object InitialState { get; }

    /// <summary>
    /// Checks if the state is the goal state
    /// </summary>
    public abstract bool IsGoalState(object state);

    /// <summary>
    /// Returns the actions available from the state
    /// </summary>
    public abstract ISet<Action> Actions(object state);

    /// <summary>
    /// Returns the state that results after performing the action on the state
    /// </summary>
    public abstract object ResultState(object state, Action action);

    /// <summary>
    ///  Returns the cost of action to reach from state to reachedState
    /// </summary>
    /// <param name="state">The state from which the action will be performed</param>
    /// <param name="action">One of the actions available in the state</param>
    /// <param name="reachedState">The state that results after performing the action</param>
    public virtual int StepCost(object state, Action action, object reachedState)
    {
        return 1;
    }
}

_

public class Node
{
    public Node(object state)
    {
        State = state;
        PathCost = 0;
    }

    /// <summary>
    /// </summary>
    /// <param name="action">The action that was applied to the parent to generate the node</param>
    /// <param name="stepCost">The cost from the parent node to this node</param>
    public Node(object state, Node parent, Action action, int stepCost)
        : this(state)
    {
        Parent = parent;
        Action = action;
        if (Parent != null)
            PathCost = Parent.PathCost + stepCost;
    }

    public object State { get; }

    public Node Parent { get; }

    /// <summary>
    /// The action that was applied to the parent to generate the node
    /// </summary>
    public Action Action { get; }

    /// <summary>
    /// The cost of the path from the initial statee to the node
    /// </summary>
    public int PathCost { get; }

    public bool IsRootNode => Parent == null;

    public IEnumerable<Node> PathFromRoot()
    {
        var path = new Stack<Node>();

        var node = this;
        while (!node.IsRootNode)
        {
            path.Push(node);
            node = node.Parent;
        }
        path.Push(node); // root

        return path;
    }
}

_

public abstract class Action
{
    /// <summary>
    /// true if it is a "No Operation" action
    /// </summary>
    public virtual bool IsNoOp()
    {
        return false;
    }

    public string Name => GetType().Name;

    public override string ToString()
    {
        return Name;
    }
}

public class NoOp : Action
{
    public override bool IsNoOp()
    {
        return true;
    }
}

public abstract class EightPuzzleAction : Action
{
}

/// <summary>
/// Move the blank tile to the left
/// </summary>
public class MoveLeft : EightPuzzleAction
{
}
// the same MoveRight, MoveTop, MoveBottom

为了做到这一点,我可以从这个基类 Problem 实现方法,并将该具体实例传递给搜索算法(接受 Problem)。

class EightPuzzleProblem : Problem
{
    private readonly int[,] _goalState =
    {
        {0, 1, 2},
        {3, 4, 5},
        {6, 7, 8},
    };

    public EightPuzzleProblem(int[,] initialState) : base(initialState)
    { }

    public override bool IsGoalState(object state)
    {
        var puzzleState = (int[,]) state;

        ......... <check if puzzleState is the same as _goalState>
    }
    ............
}

class DepthFirstSearch
{
    public IEnumerable<Action> Search(Problem p)
    {
        return DfsRecursive(p, new Node(p.InitialState));
    }

    public IEnumerable<Action> DfsRecursive(Problem p, Node node)
    {
        if (p.IsGoalState(node.State))
            return node.PathFromRoot();

        .......<simple DFS implementation>
    }
}

// usage example

var dfs = new DepthFirstSearch();
var result = dfs.Search(new EightPuzzleProblem(initialState));

if (!result.Any)
   // fail
if (result.Count == 1 && result[0].IsNoOp)
   // already at goal


foreach (var act in result)
{
    if (act is MoveLeft) .....
}

但是我发现我的类设计有一个不便之处:在具体的类实现代码中,我需要有很多来自object 的转换。有没有办法避免这种情况? 如果我将Problem 类设为通用并从Problem&lt;Something&gt; 继承ConcreteProblem,那么我将无法通过Problem 使用它...

【问题讨论】:

  • 问题出在Problem中的方法IsGoalState。它真的需要object 而不是更具体的东西吗?此外,您能否将代码尽可能限制为仅显示您的实际问题的那些类?我怀疑我们需要Node、DepthFirstSearch 和Action 来回答这个问题,对吗?
  • 更具体是什么意思? IState/State 之类的东西?也许吧,但是从IState 到MyProblemState 的转换仍然会有同样的问题,因为基类不知道表示具体问题状态需要哪些数据。

标签: c# .net oop design-patterns


【解决方案1】:

您为什么不也注入您的 GoalState 并使用如下界面使 GameState 也可插入。通过这种方式,您可以在具体类中的两个状态上实现您想要执行的任何操作,而问题类只需要调用这些函数。你也可以有不同类型的状态。

public abstract class Problem<T> where T:IGameState
{
    protected Problem(T initialState)
    {
        InitialState = initialState;
    }

    public T InitialState { get; set; }
    /// <summary>
    /// Checks if the state is the goal state
    /// </summary>
    public abstract bool IsGoalState(T state);


}

public class EightPuzzleProblem<T> : Problem<T> where T : IGameState
{
    private readonly T _goalState;

    public EightPuzzleProblem(T initialState, T goalState)
        : base(initialState)
    {
        _goalState = goalState;
    }
    public override bool IsGoalState(T state)
    {
        return _goalState.IsEqual(state);
    }
}

public interface IGameState
{
    bool IsEqual(IGameState state);
}

public class EightPuzzleGameState : IGameState
{
    private readonly int[,] _goalState =
    {
        {0, 1, 2},
        {3, 4, 5},
        {6, 7, 8},
    };

    public bool IsEqual(IGameState state)
    {
        //Compare state with _goalState
    }
}

【讨论】:

  • 感谢您的想法,我正在尝试做类似的事情 + 将检索下一个状态的方法移动到 IState 而不是 Problem。
【解决方案2】:

您实际上可以将泛型参数设置为实际状态来使Problem 泛型。

public abstract class Problem<T> where T : IState{ 
    public abstract bool IsGoalState(T state);
}

在您的派生类中,您现在可以简单地从Problem 派生,将IState 的实际类型作为泛型参数传递:

class MyDerived : Problem<MyState> {
    public override bool IsGoalState(MyState state) { ... }
}

【讨论】:

  • 但据我了解,我将无法在接受Problem 的DepthFirstSearch 方法中使用它。
  • 为此,您可以简单地引入一个通用的Problem-class,它继承了一个可以在外部使用的非通用类。
  • 你的意思是这样的? gist.github.com/AlexP11223/2f7e538202bb8b0d94906ec8e782227apublic abstract class ProblemGeneric&lt;T&gt; : Problem { public override bool IsGoalState(object state) { return IsGoalStateGeneric((T) state); } public abstract bool IsGoalStateGeneric(T state); }
  • 是的,在问这个问题之前我正在考虑这样的事情,但是为每个方法/属性创建通用包装器似乎不是一个干净无味的想法:)
猜你喜欢
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
相关资源
最近更新 更多