Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 这是参数多态性的一个例子吗?_Oop_Polymorphism_Dynamic Languages - Fatal编程技术网

Oop 这是参数多态性的一个例子吗?

Oop 这是参数多态性的一个例子吗?,oop,polymorphism,dynamic-languages,Oop,Polymorphism,Dynamic Languages,嗨,我在自学oop原理。我想知道这是否是Cardellis定义的正确例子。请开导我该示例使用cfml基于脚本的语法 <cfscript> Parent = createobject("component","webapp.model.Parent").init(); Child = createobject("component","webapp.model.Child").init(); GrandChild = createobject("component","webapp.m

嗨,我在自学oop原理。我想知道这是否是Cardellis定义的正确例子。请开导我
该示例使用cfml基于脚本的语法

<cfscript>
Parent = createobject("component","webapp.model.Parent").init();
Child = createobject("component","webapp.model.Child").init();
GrandChild = createobject("component","webapp.model.GrandChild").init();
Test = createobject("component","webapp.model.DealWithObject");
dump(Test.getNumberOfParents(Parent));
dump(Test.getNumberOfParents(Child));
dump(Test.getNumberOfParents(GrandChild));
</cfscript>

<cfcomponent>
<cfscript>
// should deal with an infinte number of abstract data types (because of common structure)
public numeric function getNumberOfParents(component arg){
  return -1 + arraylen(structfindkey(getmetadata(arguments.arg),"extends","all"));
}
</cfscript>
</cfcomponent>

Parent=createobject(“组件”、“webapp.model.Parent”).init();
Child=createobject(“组件”、“webapp.model.Child”).init();
孙子=createobject(“组件”,“webapp.model.孙子”).init();
Test=createobject(“组件”、“webapp.model.DealWithObject”);
转储(Test.getNumberOfParents(Parent));
转储(Test.getNumberOfParents(Child));
转储(Test.getNumberOfParents(孙子));
//应该处理大量的抽象数据类型(因为公共结构)
公共数字函数getNumberOfParents(组件参数){
return-1+arraylen(structfindkey(getmetadata(arguments.arg),“extends”,“all”);
}

我不相信这个pp,因为函数显式地处理
任何
参数的类型。pp的要点是函数的工作不考虑对象的类型

如果我在系统中引入一个新类型,该函数将中断,因为它没有特殊处理

编辑:我认为您更新的示例是子类型多态性,因为函数将处理对象及其任何子类型,凭借getmetadata处理对象(以及替换原则,它是子类型)。

不,只是不

多态性意味着你不必检查什么类型的东西,你只需要使用它

一个例子是(C#):

该方法可以接受从Object继承的任何类型的Object(在C#几乎所有对象中),Object实现为Equals,因此您可以使用它进行检查,而不必检查任何参数的类型。

通常,您接受某种类型的接口,以确保对象支持您想要执行的操作。

这段代码在每日WTF上找到了吗?是的,我重新阅读了Cardelli的文章。我想我的示例不好,因为我使用的是基本数据类型和抽象数据类型。我将重新布线。问题不在于原始数据类型。每当您开始编写代码检查传递的对象是否为Foo/Bar/Whatever类型时,您应该停止并尝试找到另一种解决方案(在某些特殊情况下,这是必要的,但这些情况非常罕见,即序列化和ORM在内部需要这些检查)。抱歉,我的CF知识有限,因此我不确定,但是它看起来不像原来的那么可怕,所以应该没问题。好吧,在我的示例中,它们看起来好像都是相关的,但是我没有在方法签名中指定这一点。要实现子类型多态性,我必须像getNumberOfParents(Parent arg)那样指定祖先类。这样,只接受父类型及其子类型。通过指定组件,我在接受的数据类型上引入了一个边界-将其限制为对象。我无法将数组或字符串传递给此方法-getNumberOfParents(组件arg)可以处理任何抽象数据类型(理论上,您可以创建大量的类)。
public Boolean AreEqual(Object o1, Object o2)
{
  return o1.Equals(o2);
}