假设您有一个接口 IPerson,它定义了两个成员——姓名和性别:
public interface IPerson
{
function get name():String;
function set name(value:String):void;
function get gender:String;
function set gender(value:String):void;
}
...你有两个具体的类,女人和男人,它们都实现了 IPerson 接口。
public class Man implements IPerson
{
private var _name:String;
private var _gender:String;
public function Man(name:String, gender:String)
{
this.name = name;
this.gender = gender;
}
public function get name():String
{
return _name;
}
public function set name(value:String):void
{
_name = value;
}
public function get gender()
{
return _gender;
}
public function set gender(value:String):void
{
_gender = value;
}
}
和
public class Woman implements IPerson
{
private var _name:String;
private var _gender:String;
public function Woman(name:String, gender:String)
{
this.name = name;
this.gender = gender;
}
public function get name():String
{
return _name;
}
public function set name(value:String):void
{
_name = value;
}
public function get gender()
{
return _gender;
}
public function set gender(value:String):void
{
_gender = value;
}
}
然后,您最终可以执行以下操作:
var crowdOfPeople:ArrayCollection = YourCrowdOfPeopleClass.getInstance();
for each (var p:IPerson in crowdOfPeople)
{
trace(p.name);
trace(p.gender);
}
...也就是说,对 Man 和 Woman 的具体实现采取行动(在这种情况下,跟踪其属性),就好像它们是同一种对象一样,因为它们都符合 IPerson 接口(即两者定义名称和性别属性)。
它是面向对象的多态性原则在起作用——有时您会听到它作为信条,“编程到接口,而不是实现”。希望有帮助!