extending a class and implementing an interface - actionscript-3

I am creating objects for a game, they are all sprites. but I also want them to implement an interface. Is it possible to do both ? If not, how can i have an object have the capabilities of a sprite and also have it implement an interface. I am wanting to create another class that checks all my objects to see what datatype they are and evaluate them accordingly

It is possible for all ActionScript objects to both implement an interface and extend a class. Here's an example:
public class RedZoid extends Sprite implements IColoredZoid
Furthermore, the is keyword works with interface implementations:
var z1:RedZoid = new RedZoid();
if (z1 is IColoredZoid) {
// This branch will be hit, since the interface is implemented
}

Related

Can the Proxy class be used in AS3 on existing classes?

The AS3 Proxy class extends Object and exposes methods that you can override to handle the addition/removal and getting/setting of properties on the object in a universal fashion.
It appears that existing objects such as MovieClip, Sprite, etc. do not inherit from the Proxy class, so it would seem to preclude the possibility of adding such functionality to existing display object classes.
I've created a layout framework with a base display object class called GUIControl that inherits from MovieClip, and I was hoping to add data-binding functionality to it by overriding the Proxy class's setProperty method, so I could handle property assignments with a single handler to make all properties function as binding sources by default.
Is there some way to utilize the Proxy class's functionality on existing classes, or am I stuck building classes from scratch based on Proxy?
You may create a wrapper class for MovieClip and set property on the wrapper. You should override other functions in Proxy and call the relative functions on MovieClip.
Here is an example
import flash.display.MovieClip;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public class MovieClipWrapper extends Proxy
{
public function MovieClipWrapper(target:MovieClip)
{
super();
_target = target;
}
private var _target:MovieClip;
override flash_proxy function setProperty(name:*, value:*):void
{
//set data on target movieClip, or call the notify functions
}
}
No, it cannot be used on existing classes. The worst part is that rules out using Proxy on any display list classes. There is no way to alter a property on a display list class and have the Proxy class intercept and handle the setting or getting of such a property value. Proxy is useful only as a base class for new classes (ideally dynamic classes), where you want to intercept and run logic when properties are set/retreived/removed.
Futhermore, Proxy is useless for trying to wrap something like the Dictionary class, since Proxy's interface methods rely on QName and String-type keys exclusively, which makes it impossible to enumerate over, get, or set Dictionary values that use object instances as keys... something Dictionary supports unlike associative arrays or normal Objects.

Interfacing and Game Architecture in Actionscript 3

I am in the midst of creating the architecture for my new Point and Click game in the Starling framework. It is set to be big in size, so I am trying to make sure to use best Object Oriented practises to ensure I do not A) Repeat the same methods. B) Keep it sustainable and clean.
I was unaware of Interfacing as a way to contract all classes. To keep everything consistent and to ensure that sub classes have the methods to function correctly. Let us look at an example of a player class i have created.
public interface IPlayer {
function changeDirection():void;
function walkToPosition():void;
function pickUpItem():void;
}
class AbstractPlayer extends Sprite implements IPlayer {
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
class Player extends AbstractPlayer {
override protected function walkToPosition():void {}
override protected function pickUpItem():void {}
}
I am aware that AS3 Does not support Abstract Classes natively. But I choose to have it in this form as it makes sense to. What I do not understand is why the interfaces only support public methods. Doesn't that defeat the whole purpose of having an interface; so you know what methods are needed for a player. Declaring only the public functions of the player class seems like a half job.
A verbose explanation of this concept and perhaps a more advanced solution to how this could be structured would be of great benefit.
Many Thanks,
Shaun
An interface is a collection of method declarations that allows unrelated objects to communicate with one another.Hence public access control identifiers for implemented methods.In a typical interactive context often a need arises to modify or control behavior of an object in question externally.In such a case, behavior-control may ideally be accomplished through an interface.Obliviously only methods put into a public namespace are accessible externally.Bearing in mind that attributes of an object should not be be directly modified by external code but only through an interface is good practice of Object Oriented Design. Assuming that a need arises of an object to have more than one point of access control(behavior control); one for external purposes and the other for internal purposes respectively, then putting all behavior in one interface defeats the objective.The following may help to achieve the objective(because you said it's big in size).
Put behavior in an interface you think should be accessible externally.
Define Mediator to encapsulate view-code-mediation:-listen for user triggered events, update view send notifications to other tiers of the application.
Define Model for data purposes.
Define executable commands to be called within your application.
See if you can promote as much lose coupling as possible among the tiers.The goal is to write as much less code as possible and not boiler-plate in nature.I recommend that you use a framework such as robotlegs if really your project is that big.The framework will take care of dependency injection and along the way lift off the burden of writing boiler-plate code.
I Hope the foregoing helps. Thanks.
The interface is acting as an outline of required members to be implemented in the classes using said interface. Therefore the interface methods never being called directly and only being used in the classes implementing them require no access modifiers.
Now you're correct AS3 does not support abstract classes, BUT there is a way to implement an "abstract" class AS3 as per the design. So here is what that might look like with your code:
public interface IPlayer
{
function init():void;
function changeDirection():void;
function walkToPosition():void;
function pickUpItem():void;
}
public class AbstractPlayer extends Sprite implements IPlayer
{
public function AbstractPlayer() {
init();
}
protected function init():void {
throw new IllegalOperationError( "Abstract method, must be overridden in subclass" );
}
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
public class Player extends AbstractPlayer
{
public function Player() {
super();
}
override protected function init():void {
//implementation
}
}
Abstract classes having method implementation by default will require subclasses to override these methods ( see init() and error thrown ) keeping strict usage of the parent class method and members.
This is the basic abstract class design for AS3. This is also the begining to a Factory Method pattern which you can read more on here: http://www.adobe.com/devnet/actionscript/articles/ora_as3_design_patterns.html
Now the more reusable design for this might be to generalize your class names a bit more, perhaps something more like this:
public interface IEntity
{
function init():void;
function changeDirection():void;
function walkToPosition():void;
}
This would be assuming that more game objects other than your Player class will have use of the methods in the IEntity interface.
Now your Player class can become a new object of type Entity:
public class Entity extends Sprite implements IEntity
{
public function Entity() {
init();
}
protected function init():void {
throw new IllegalOperationError( "Abstract method, must be overridden in subclass" );
}
public function changeDirection():void {}
protected function walkToPosition():void {}
protected function pickUpItem():void {}
}
Now in regards to the design, since abstract classes are just a tool like any other there are many different designs to take using it and it really depends on your project. I would recommend sifting through the aforementioned link to the "Factory Method" pattern and some of the other designs to see what fits your needs.
An interface defines the way other classes interact with a specific implementation of that interface. Other classes cannot call implementation's private methods directly - there's no need for the interface to define them.
Let's say we have two subclasses of AbstractPlayer: Player and AIPlayer. The Player class would probably include methods to listen for specific input events and to respond to them accordingly, like onKeyUp or onMouseClick, which should be private: there's no need to external classes to know how the player is controlled. The AIPlayer on the other hand is controlled by some strategies you define in your code, therefore instead of listening to user's input, it should keep track of Player's actions and react accordingly. This class does not need onKeyUp or onMouseClick methods, so why put them in interface?

AS3: Best way to include non-specific functions in to class

Say I have the following set up of classes...
Road - extends MovieClip Car - extends Road
Controller - extends Car
And I want to incorporate some common Mathematical functions in them all to make them faster e.g.(replacing Math classes with some speedy bitwise versions).
What is the best way to incorporate these functions into all of them without writing the functions in the classes or extending from class of the functions. Is importing the class into each the fastest way or is their a better way?
You can create a public function that you can import into any class. Some examples in the base language are navigateToURL() and getTimer(). These are just public functions in a package, not classes.
So create a public function like so
package nameOfYourPackage{
public function doSomething(a:arguments):returnType
{
// Stuf the function does goes here;
}
}
then you can import it into any class like so:
import nameOfYourPackage.doSomething;
and then youc an call it anywhere in a class that imports it as:
doSomething(args);
I agree with the comments that your design may needs some work. You can't use a Class in another Class without an import statement that refers to it in some way--even if you're just importing an Interface that the Class implements.
The most flexible way to handle this is to have the functional object be passed in to the object that needs it, rather than having that object create the instance itself. This will allow you to swap out a different implementation when you need to (for instance, you might want to use a mock instance for unit testing, or you might need slightly different functionality optimized for a mobile device).
You can pass in the instance either in the Constructor or use a property (which would allow you the freedom to change out the implementation at runtime).

AS3 Prototypes - are they just static variables?

A reference to the prototype object of a class or function object. The
prototype property is automatically created and attached to any class
or function object that you create. This property is static in that it
is specific to the class or function that you create. For example, if
you create a class, the value of the prototype property is shared by
all instances of the class and is accessible only as a class property.
Instances of your class cannot directly access the prototype property.
A class’s prototype object is a special instance of that class that
provides a mechanism for sharing state across all instances of a
class. At run time, when a property is not found on a class instance,
the delegate, which is the class prototype object, is checked for that
property. If the prototype object does not contain the property, the
process continues with the prototype object’s delegate checking in
consecutively higher levels in the hierarchy until Flash Player or the
Adobe Integrated Runtime finds the property.
Note: In ActionScript 3.0, prototype inheritance is not the primary
mechanism for inheritance. Class inheritance, which drives the
inheritance of fixed properties in class definitions, is the primary
inheritance mechanism in ActionScript 3.0.
So, from this I get the impression that prototypes are just static variables.. am I right?
Not exactly, a function implemented as a prototype is still executed as instance method. In a static function you don't have access to this.
Also it doesn't mean setting a prototype value to something is setting the value for every instance. It's only the fallback value, if an object of that class isn't setting it explicitly.
var o1:Object= {};
var o2:Object= {};
Object.prototype.foo = "foo";
o1.foo = "bar"
trace(o1.foo) // bar
trace(o2.foo) // foo

When should I use/examples of nested classes?

Please retag this question to include languages to which it is relevant
So my java book had a whole chapter on nested classes, but ended on the note that you should only really use them when it comes to "modeling composition relationships and implementing internals of a class you want to hide". So lets discuss when you would want to use nested classes and some examples.
A nested/inner class is just a class that's only ever used specifically in the context of another class, which doesn't have it's own class file. If it's linked to an instance, it can only be instantiated in the context of a parent class instance; it can see private data, or only private static data if it's a static class.
The java developer site has a nested classes tutorial with one example:
http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html
A couple examples of usage:
Hide a concrete implementation of an
interface:
(Thinking of a database session for a tool like Hibernate): Suppose you have a Session interface, and a SessionFactory which returns an instance of a Session. The SessionImpl concrete class that implements the Session interface could be an innner class of the factory that knows how to construct and initialize it.
Supply information by implementing an
interface:
In the Wicket web framework, each GUI component has an associated "model", whose job is to wire data to the component. The interface looks something like:
public interface IModel extends IDetachable {
public Object getObject();
public Object setObject();
}
Suppose you have some special logic to retrieve data for a custom GUI component that you've written. Since no other component retrieves data the same way, you could use an anonymous class at the point where the IModel is supplied to take care of the data retrieval. If you have another point in the same class where you need to reuse your IModel implementation, you could make it an inner class. Later, if you need the model elsewhere, you could convert it to a top-level class.
Generally you use an inner class in a situation where you need a class definition, but that class is only usable or only makes sense in the context of the parent class.
A real life usage i had with nested classes, was in a global settings object.
The parent class was a Singleton, with nested classes as settings categories.
Settings
File settings
Print settings
Etc.
There was no real point in making the inner object as separate classes, as their would be no use for them outside the settings class scope.
I use nested classes for encapsulating algorithms that would be usually done as a method with lots of arguments. I use class that has raw data and I put algorithms into separate file in nested class (using partial keyword). That way I can put properties for that algorithm and its (working) data lives after algorithm is done.
I know that can be easily done without nested classes but this feels right because algorithm is purposely built for parent class.
public partial class Network
{
partial void initFDLF()
{
fdlf=new FDLF(this);
}
public FDLF fdlf;
public class FDLF
{
internal bool changed=true;
internal bool pvchange=true;
public double epsilon = 0.001;
public bool fdlfOk=false;
public void init(){...}
public void run(){...}
...