Flash / Flex / ActionScript/Class/Composition
Версия от 09:19, 26 мая 2010; (обсуждение)
Class composition
package
{
public class Employee
{
public function doWork():int
{
return 1;
}
}
}
class Manager
{
protected var employees:Array;
public function Manager(numberOfEmployees:int)
{
employees = new Array();
for (var i:int = 0; i < numberOfEmployees; i++)
{
employees[i] = new Employee();
}
}
public function delegateWork():int
{
var totalWork:int = 0;
for each (var employee:Employee in employees)
{
totalWork += employee.doWork();
}
return totalWork;
}
}
class Company
{
public function Company()
{
var manager:Manager = new Manager(10);
var completedWork:int = manager.delegateWork();
trace(completedWork); //10
}
}
Inheritance vs. Composition
package
{
public class House
{
public var kitchen:Kitchen;
public var livingroom:LivingRoom;
public var bedrooms:Array;
public function House(numberOfBeds:int)
{
kitchen = new Kitchen();
livingroom = new LivingRoom();
bedrooms = new Array();
for (var i:int = 0; i < numberOfBeds; i++)
{
bedrooms[i] = new Bedroom();
}
}
}
}
class Kitchen{
}
class LivingRoom{
}
class Bedroom{
}