fufonzo
fufonzo

Reputation: 181

AS3 Polymorphism: Changing classes from within that class

This is a very simplified version of my issue but should be enough for me to solve my problem.

Let's assume I have classes DressingRoom, Person, Hat, Badge, and Foreman and the app allows you to give a person different types of hats while they're in the dressing room, and if it's a foreman, he can get a badge as well. What I'd like is for the user to become a Foreman if you give him a white hat and have him just be a regular person if it's not.

Is it possible to set a certain class to a subclass of itself within Person rather than have to do it in Dressing Room class (which would be easy to do).

public class DressingRoom{
  public var length:int;
  public var occupant:Person;
}

public class Person{
  public var name:String;
  public var hat:Hat;

  public function hatChanged():void{
    if (hat.color==0xFFFFFF){
      this =  new Foreman(name,hat);
    }
  }
}

public class Hat{
  public var size:int;
  public var color:uint;
}

public class Foreman() extends Person{
  public var badge:Badge;

  public function hatChanged():void{
    if (hat.color!=0xFFFFFF){
      this =  new Person(name,hat);
    }
  }
} 

Upvotes: 1

Views: 718

Answers (3)

eleven
eleven

Reputation: 6847

Strange question :) You can use composition instead of inheritance. It could looks like this:

public interface IHat{
  function get status():HatStatus
}

public class ForemanHat implements IHat{
  private const status:ForemanStatus = new ForemanStatus();
  public function get status():HatStatus {return status;}
}

public class Person{
  private var status:HatStatus;

  public function setHat(hat:IHat):void{
    status = hat.status;
  }

  public function get status():HatStatus{ return status}
}

You can add more hats simply.

Upvotes: 1

Daniel
Daniel

Reputation: 35684

seems like a good candidate for the decorator design pattern. there's quite a bit on that and as at as3dp.com

Upvotes: 1

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

The direct answer to your question is NO. You're on the right track with your dressing room concept though where you hold occupant:Person in a wrapper class, and check to see if it's of type Foreman when needed.

Upvotes: 1

Related Questions