views:

39

answers:

3

I have 3 types of objects: Red, Green, and Blue. I have 3 kinds of devices that handle each type of object, respectively. No device can handle more than 1 type of object. Each "object handler" has a reference to an object which it is currently handling.

In Java I'd do something like this:

public class RedObject {}
public class GreenObject {}
public class BlueObject {}

public class AbstractHandler<T> {
   public T myObject;
}
public class RedHandler extends AbstractHandler<RedObject> {}
public class GreenHandler extends AbstractHandler<GreenObject> {}
public class BlueHandler extends AbstractHandler<BlueObject> {}

Is there any non-horrible way to do this in a language without generics? I don't want to define the myObject property separately on each subclass since then I lose the advantage of inheritance.

(If it helps, the language I'm trying to do this in is actionscript 3.)

A: 

Have a common base class for the red, green and blue objects. Pass that to the handler. Have each handler assert that it is receiving the correct descendant class of the base class.

In Delphi:

type
  TBaseObject = class(TObject)
    ...
  end;
  TBaseObjectClass = class of TBaseObject;

  TRedObject = class(TBaseObject)
    ...
  end;

  TAbstractHandler = class(TObject)
  private
    MyObject: TBaseObject;
  protected
    class function HandlesClass: TBaseObjectClass; virtual; abstract;
  public
    constructor Create(const aObject: TBaseObject);
  end;

  TRedHandler = class(TAbstractHandler)
  protected
    function HandlesClass: TBaseObjectClass; override;
  end;

constructor TAbstractHandler.Create(const aObject: TBaseObject);
begin
  Assert(aObject.InheritsFrom(HandlesClass), 'Object does not descend from proper class');
  ...
end;

class function TRedHandler.HandlesClass: TBaseObjectClass;
begin
  Result := TRedObject;
end;
Marjan Venema
A: 
abstract class BaseObject
{
    //has common properties for all derived classes

}
class ObjectRed : BaseObject
{
 // expended by own properties  
}
abstract class Basehandle
{
    private BaseObject _baseObject;
    //you can handle the common propertyes of base object type
    protected Basehandle(BaseObject baseObject)
    {
        _baseObject = baseObject;
    }
}
class Redhandle:Basehandle
{   // access only Objectred type
    private ObjectRed _objectRed;
    public Redhandle(ObjectRed objectRed):base(objectRed)
    {
        _objectRed = objectRed;
        //handle the extented props.
    }
}
Arseny
A: 

If RedObject, GreenObject, and BlueObject all implement a common interface, you could build your handler class to work with that interface.

mikemanne