java - 我怎样才能拥有这两个构造函数?
问题描述
我正在为源自尼泊尔的名为 Tigers and Goats(或 Tigers and Sheep)的游戏制作基于树的 AI。我现在开始为树创建类,但是我遇到了一个错误,我的构造函数是相同的,尽管它们使用不同类型的列表。
这是我的两个构造函数:
public MoveTree(List<MoveTree> children, MoveTree parent)
{
this.children = children;
this.parent = parent;
}
public MoveTree(List<Move> moves, MoveTree parent)
{
this.moves = moves;
this.parent = parent;
}
如何在仍然拥有两个构造函数的同时避免此错误?我希望能够在不过多更改构造函数的情况下做到这一点,这样我就可以有不同的方式来实现这个类以用于不同的目的
解决方案
你不能两者兼得。使用构建器模式(正式风格 - 此处未显示)或工厂方法(更容易 - 显示):
private MoveTree(MoveTree parent) {
this.parent = parent;
}
public static MoveTree createWithMoveTree(List<MoveTree> children, MoveTree parent) {
MoveTree moveTree = new MoveTree(parent);
moveTree.children = children;
return moveTree;
}
public static MoveTree createWithMoves(List<Move> moves, MoveTree parent) {
MoveTree moveTree = new MoveTree(parent);
moveTree.moves = moves;
return moveTree;
}
推荐阅读
- javascript - vue.js 中的 .includes() 和 .filter()
- mongodb - 我可以依靠 mongo 始终如一地处理来自许多不同来源的许多 $inc 都更新同一个文档吗?
- html - Chrome 浏览器默认设置不会停止使用滚动条,除非在运行我的代码时
- c# - 按降序排序datagridviewcolumn C#
- c# - 当我尝试在 C# http Client 中以 JSON 格式获取大量数据时出现错误
- java - Lambda 表达式如何在 Java 中推断类型?
- html - 无法执行 jquery 函数
- python - 如何通过键比较两个数据帧并创建一个新数据帧,但只保留不在第一个数据帧中的键?
- sql - Postgres:在字段中查找具有一个特定值的记录
- regex - 正则表达式替换连字符?