Factory Pattern:
Factory Patterns :- How to add objects to the stage
Category : Games Author : Raina
It acts as intermediary class between the client and the concrete class. This is called a creator class. It allows the client to access objects without specifying the exact class of object. This is achieved by creating the objects by separate method in the creator called a createFruits. The main purpose of the factory method is to instantiate objects and return them.
Explaination :
we define Fruit class as an abstract class because we want to implement default behavior common to all inherited Fruit subclasses in the definition. The default behavior is defined in a
method called position( ) to set the X and Y coordinates , speed (movement on stage) and initial angle of the sprite. Fruit class also defines a method called move() which included addEventListener ’EnterFrame’ for sprite to move on stage which is inherited to all subclasses by default ,to change the behaviour you override the specfic method.
Here protected function doMove(e:Event) move the sprite in +ve X-axis with speed which will be set in Client Class .
this.x+=speed;
we will check the location of sprite on stage with if condition ,if location is greater than stageWidth then we will set speed = -speed so as to reverse the direction of sprite.
if (this.x>stage.stageWidth-30) {
speed=- speed;
}
As of now we have Fruit concrete class .In this section we are creating Mango,Apple and Orange classes which are extended from parent Fruit class and follow the OOP inheritance behaviour
Key code line for these subclasses is
package {
public class Mango extends Fruit {
//no need to add or override methods as it will inherit default behaviour from Parent
}
}
Apple class code is same as Mango we can set different positions ,speeds, and angles of sprites in client class shown in last section.
Note : In Orange class we want Orange to in y direction with continuous rotation along with its default x movement.
Explanation: To override function simply add override as shown in code snippet to function with same function name and arguments.
Here to inherit x-movement from parent class we will use super.doMove(e); .