我应该使用从可实例化类继承的单例类还是有另一种更好的模式?
我有一个名为 ArtificialIntelligenceBase 的类,您可以从中创建自己的人工智能配置,将一些变量发送到构造函数,或者您可以创建一个继承自 ArtificialIntelligenceBase 的类,并在这个新类的构造函数中只需调用函数 super() 即可配置的参数。
我还在课堂上创建了一些人工智能示例:AIPassive、AIAgressive 和 AIDefective。显然它们都继承自ArtificialIntelligenceBase。
关键是基类中只有很少的公共函数。基类中的变量是只读的,非公共函数受到保护,以防您在创建另一个预定义的 AI 时需要对它们进行一些修改。
您还可以创建另一个 AI,只需调用基类并在构造函数中发送一些参数,如下所示: new ArtificialIntelligenceBase(param1, param2, param3, param4);
我一直在努力将这些类作为单例,因为这些类永远不会改变,而且一旦设置,它们的变量就永远不会改变。
问题是:单例是执行此操作的最佳模式吗?因为我不确定。
PD:您不需要解释任何内容,只需提及名称,我将搜索它是如何工作的
PPD:我正在使用 AS3 进行开发。以防万一有帮助
谢谢
I've got a class called ArtificialIntelligenceBase from which you can create your own artificial intelligence configuration sending some variables to the constructor or you can make a class that inherits from ArtificialIntelligenceBase and in the constructor of this new class just call the function super() with the parameters of the configurations.
I've also created some examples of artificial intelligences in classes, AIPassive, AIAgressive and AIDefensive. Obviously all of them inherits from ArtificialIntelligenceBase.
The point is that there're only few public functions in the base class. The variables in the base class are read only and the non public functions are protected in case you need to apply some modifications on them when created another pre-defined AI.
You can also create another AI just calling the base class sending some parameters in the constructor like this: new ArtificialIntelligenceBase(param1, param2, param3, param4);
I've tought about make the classes as a singleton because the classes can never change and once setted, their variables never change.
The question is: Is the singleton the best pattern to do this? Because I'm not sure.
PD: You don't need to explain any patter, just mention the name and I'll search for how it works
PPD: I'm developing in AS3. Just in case it helps
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,单例是邪恶的。我也不认为你的情况有任何理由使用单例。听起来您正在使用自己版本的 工厂方法 模式(以某种方式使用构造函数?)或者可能是一个 原型 (我不知道 AS3位),但如果您正在寻找其他模式,其他一些模式是抽象工厂和构建器。
不过,您不需要使用单例模式来限制自己只为每种类型的类使用一个实例。这无助于避免冗余。
In general, singletons are evil. I don't see any reason in your case to use a singleton, either. It sounds like you're using your own version of a factory method pattern (using a constructor somehow?) or maybe a prototype (I don't know AS3 one bit), but if you're looking for other patterns a couple of other ones are abstract factory and builder.
You don't need to use the singleton pattern to limit yourself to using only one instance per type of class, though. It doesn't help avoid redundancy.