ActionScript 3 Singleton instantiation - advice - actionscript-3

I have an AS3 Singleton:
package
{
public class Singleton
{
public function Singleton(enforcer:SingletonEnforcer):void
{
if(!enforcer){throw new Error("Only one instance of Singleton Class allowed.");}
}
private static var _instance:Singleton;
public static function getInstance():Singleton
{
if(!Singleton._instance)
{
Singleton._instance=new Singleton(new SingletonEnforcer());
}
return Singleton._instance;
}
}
}
class SingletonEnforcer{}
Consider prop and func() to be a property and method respectively of the Singleton class.
How should I access them?
1. Make them static and use this:
Singleton.getInstance();
Singleton.prop;
Singleton.func();
2. Not make them static and use this:
Singleton.getInstance().prop;
Singleton.getInstance().func();
Does it matter, or is it just visual prefference?
Thank you.

The reason to use a singleton instance is so that you can have class members used in a (relatively) static way.
I won't get into the arguments over whether or not to use a singleton here, there's a very long debate over whether it's a good pattern or not.
Typically, when singletons are used, you store access to them in a local variable and use them like any other class instance. The primary difference, is instead of using:
foo = new Foo();
You use:
foo = Foo.instance;
//Actionscript supports properties which makes this a self-initializing call
-or-
foo = Foo.getInstance();
Followed by
foo.bar();
foo.baz();
foo.fizz = 'buzz';
This doesn't mean that Foo can't have static members of the class, but the rules for adding static members on a Singleton are the same for adding static members to any other class. If the function belongs to the instance, it should be used on the instance, if it belongs to the class, it should be static.

Related

conceptual issue in inheritence property of actionscript-3

say, Child class is inheriting Father class and Father class is inheriting spark TextArea class. now from an mxml file (in FLEX4), i am creating multiple objects of Child class. Father class have few static attributes whose values are set by private methods, calling from constructor. Now the question is: all these static attributes are set every time while Child class objects are being created one by one?
If answer is yes then Is it possible that Father class static attributes are set only once and not depends upon the number of Child class objects creation.
Please provide any suggestion or tips
Thanks in advance.
If you are setting static variables from an object's constructor or methods called from the constructor, then yes, they will be set every time. In order to prevent that, just check whether the variable is already set.
public class Foo {
public static var bar:Object;
public Foo(value:Object) {
if (!bar) {
bar = value;
}
}
}
First decide if those static members are really all that important to store as statics because statics are associated with a Class and not an instance it's usually a signal that you're probably doing something you shouldn't if instances are modifying or reading static members. You probably should use a factory method if you need to share that information with the instances. However, if you're sure you should do it then you can use a static initializer block to initialize the members when the class is loaded. Downside is that block throws an exception it can be hard to track down:
public class SomeObject {
private const _someStaticMember : String;
private const _someOtherStaticMember : SomeOtherObject;
static {
_someStaticMember = "foobar";
_someOtherStaticMember = new SomeOtherObject();
}
}

AS3 - Retype/Cast an inherited variable permanently in a subclass?

Possibly bad practice but I'm not well versed in software design anyway (I'm sure this question would have been asked before but I can't seem to find the right terminology)...Anyhow, it's just another curiosity of mine I'd like to have answered.
So I have worked in a way where I type a base class variable to type Object or Sprite or something similar so that in my subclasses, I can instantiate my custom classes into them and store it. And when I access it, I just cast that variable to ensure I can access the methods.
Take this example, so that you know what I'm talking about:
public class BaseClass
{
protected var the_holder_var:Object;
public function BaseClass()
{
//Whatever abstract implementation here...
}
}
Now, my subclasses of that base class usually use an interface but for simplicity sake, I'll just write it without it.
public class AnExtendedClass extends BaseClass
{
public function AnExtendedClass()
{
//Instantiate my own class into the base class variable
this.the_holder_var = new ACustomClassOfMine();
//Then I can use the 'hackish' getter function below to
//access the var's functions.
this.holder_var.somefunction()
}
private function get holder_var():ACustomClassOfMine
{
return this.the_holder_var as ACustomClassOfMine;
}
}
This works and I'm sure it will make some ppl cringe (I sometimes cringe at it too).
So now, my question, is there a way to recast/retype that base var in my extended subclass?
kinda like this:
public class ExtendedClass extends BaseClass
{
//Not possible I know, but as a reference to see what I'm asking about
//Just want to change the type....
override protected var the_holder_var:ACustomClassOfMine;
public function ExtendedClass()
{
//Then I can forget about having that hackish getter method.
this.the_holder_var = new ACustomClassOfMine();
this.the_holder_var.somefunction();
}
}
I was thinking of typing most of my base class vars that I use as holders as type * and retyping them as I extend the class. (I could use it here too but yeah...)
Thoughts? Comments? Ideas?
I actually think your code (apart from the hypothetical addition at the end) is pretty alright. The practise of adding accessors to solve the type issue you're dealing with is a solid one. I would advise to rename the accessor to show it is a cast, maybe get holderVarAsCustom():ACustomClassOfMine (I'm also not a big fan of the underscores, that's another language's convention), but that's personal preference. What I'd do to solve your last problem is just create a matching setter function:
private function set holderVarAsCustom(value:ACustomClassOfMine):void {
this.the_holder_var = value;
}
This way you can access the correctly typed holder var for both read and write operations with complete type safety:
holderVarAsCustom = new ACustomClassOfMine();
holderVarAsCustom.someFunction();
I would definately advise against dropping the type safety by including arrays and what not, that just makes it unstable.
I must admit that i'm a little confused as to why you want to do this, but here goes. Could you not utilise the fact that Array's can hold different data types. So something like this:
public class BaseClass
{
protected var customStorage:Array;
public function BaseClass()
{
//Whatever abstract implementation here...
}
}
You could then access it with an associative method and a property:
public class AnExtendedClass extends BaseClass
{
private static const myName:String = "myName";
public function AnExtendedClass()
{
//Instantiate my own class into the base class variable
customStorage[myName] = new ACustomClassOfMine();
objectIWant.somefunction()
}
private function get objectIWant():ACustomClassOfMine
{
return ACustomClassOfMine(customStorage[myName]);
}
}
Is that any better?
I would not try to tinker this behaviour, since you can't change the declared type of a variable once declared, no matter how hard you try.
What I do in such cases, I either cast the variable if I use it sparingly or the object it references may change, or I add another variable with the type I want and let the other variable point to the new one. Like this:
public class A {
protected var object:Object;
public function A() {
//Whatever abstract implementation here...
}
}
and
public class B extends A {
protected var other:MyClass;
public function B() {
super();
this.other = new MyClass();
this.object = this.other;
}
}
Having it this way, class A uses the object via the this.object reference, and class B can use the this.other or both. But both references point to the same object. The only issues with this are:
having two references for in the same class to the same object is ugly (so are untyped variables and casts)
if the object one of them may point can change during runtime, you must be really carefull to synchronize these changes

Language Agnostic Basic Programming Question

This is very basic question from programming point of view but as I am in learning phase, I thought I would better ask this question rather than having a misunderstanding or narrow knowledge about the topic.
So do excuse me if somehow I mess it up.
Question:
Let's say I have class A,B,C and D now class A has some piece of code which I need to have in class B,C and D so I am extending class A in class B, class C, and class D
Now how can I access the function of class A in other classes, do I need to create an object of class A and than access the function of class A or as am extending A in other classes than I can internally call the function using this parameter.
If possible I would really appreciate if someone can explain this concept with code sample explaining how the logic flows.
Note
Example in Java, PHP and .Net would be appreciated.
Let's forget about C and D because they are the same as B. If class B extends class A, then objects of type B are also objects of type A. Whenever you create an object of type B you are also creating an object of type A. It should have access to all of the methods and data in A (except those marked as private, if your language supports access modifiers) and they can be referred to directly. If B overrides some functionality of A, then usually the language provides a facility to call the base class implementation (base.Foo() or some such).
Inheritance Example: C#
public class A
{
public void Foo() { }
public virtual void Baz() { }
}
public class B : A // B extends A
{
public void Bar()
{
this.Foo(); // Foo comes from A
}
public override void Baz() // a new Baz
{
base.Baz(); // A's Baz
this.Bar(); // more stuff
}
}
If, on the other hand, you have used composition instead of inheritance and B contains an instance of A as a class variable, then you would need to create an object of A and reference it's (public) functionality through that instance.
Composition Example: C#
public class B // use A from above
{
private A MyA { get; set; }
public B()
{
this.MyA = new A();
}
public void Bar()
{
this.MyA.Foo(); // call MyA's Foo()
}
}
depending on the access level (would be protected or public in .NET), you can use something like:
base.method(argumentlist);
the base keyword in my example is specific to C#
there is no need for an instance of class A, because you already have a class A inherited instance
Basically you need a reference to the parent class.
In PHP:
parent::example();
From: http://www.php.net/manual/en/keyword.parent.php
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>
I find that the best way to tame the complexity of inheritance is to ensure that I only make B inherit from A when it really is a specialization of the superclass. At that point, I can call A's methods from inside B just as if they were B's own methods, and if B has overridden them then I can only suppose that this must be for a good reason.
Of course, quite often it is useful for B's implementation of a method to invoke A's implementation on the same object, generally because the subclass is wrapping extra behavior around the superclass's basic definition. The way in which you do this varies between languages; for example, in Java you do this:
super.methodName(arg1, ...);
Here's a quick Java example:
public class Aclass
{
public static void list_examples()
{
return("A + B = C");
}
}
public class Bclass extends Aclass
{
public static void main(String [] args)
{
System.out.println("Example of inheritance "+list_examples);
}
}
Note that the method for accessing the parent class shouldn't change. Because you are extending you shouldn't have to say parent:: or anything unless you are overriding the parent method / function.
It seems to me that extending your class might not be your best option. Class "B", "C", and "D" should only extend class "A" if they are truly an extension of that class, not just to access some method. For instance "Huffy" should not extend "BrandNames" just because "Huffy" is a brand name and you want access to one of the methods of "BrandNames". "Huffy" should instead extend "Bicycle" and implement an interface so the methods of "BrandNames" can be used. An additional benefit here is that (in Java) multiple interfaces can be used but a class can only be extended once. If in your example class "B"' needed to access a method from class "A" that could work, but if class "C" needed to access a method from class "A" and class "'B"' then you would have to use an interface in class "'C".

Should a class ever have static and non-static members

I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.

does static methods need to use static properties?

I am using as3. Just a simple question.
If I created a static method. say I decide to call on other methods within that static method. Do those methods I call on need to be static as well? what If I used some of the properties. Not to store data permanently, but just within that process. Do those properties need to be static ??
Yes. If anything is called static that means that it is related not to the current instance of the class but to the whole class therefore it must act instance-independent, e.g. use other static fields and methods if needed.
No, they do not. You can use any type of variable/method from within a static method, including, of course, local variables. However, there is no concept of "this" in a static method, since the method is not being executed on an instance, but on the class itself. Therefor, the following (inside a class declaration) is illegal:
public var myInstanceVariable : int;
public static function myStaticMethod() : void
{
// Illegal:
myInstanceVariable = 1;
// Illegal (same as above, "this" is implicit):
this.myInstanceVariebl = 1;
// This however is legal (local variable):
var localVal : int = 1;
}
The references to myInstanceVariable above are illegal because that variable is an instance variable, which is not accessible to the static method. Because static methods are not executed on an instance in the first place, the "this" special variable is not valid.
If you wanted to, you could keep a static reference to an instance, and execute methods on said instance. That's the key idea behind the common singleton pattern.
private static var _INSTANCE : MyClass;
public static function myStaticFunction() : void
{
_INSTANCE.doSomething();
}
Here, the _INSTANCE variable can be referenced from the static method, because the variable itself is declared as static.
To avoid confusion, there are actually answers to both the questions you asked:
Do method calls within a static method need to be static? Li0liQ answered this.
Do variables used within a static method need to be static? richardolsson answered this.
To summarize, within a static method, you can only access static variables and methods EXCEPT if you define local variables within the scope of the static method.
private var instanceVar : MyClass;
private static var staticVar : MyClass;
public static function myStaticFunction() : void
{
// Illegal, instance variable
instanceVar = new MyClass( 1 );
// Illegal, method on instance variable
instanceVar.someMethod();
// Legal, scoped local variable
localVar : MyClass = new MyClass( 1 );
// Legal, method on scoped local variable
localVar.someMethod();
// Legal, static variable
staticVar = new MyClass ( 1 );
// Legal, method on static variable
staticVar.someMethod();
}
It makes sense if you think about it a little, but it's not an entirely clear concept at first.