What do you call a "singleton" that allows a public constructor for additional instances? - constructor

I'm making a class that supports the Singleton use (one instance is available), yet it also supports normal instance use (via a public constructor).
If you only want one, use that one. If you want 5, new them up.
I clearly can't call this singleton, or some other dev will come along and make my constructor non-public. What can I call this to indicate how it is to be used? Naming is hard.
Some guesses for your amusement:
"StaticallyAvailable"?
"ThreadReady"?
"SingletonOptional"?

It sounds like you've got a "default instance". You could name your object along those lines.

Usually the point of a singleton is for an object that has an unique instance. If multiple copies of the class can exist, then it means that "oneness" is not a necessary behavior. This is just like any other object.
Probably, the reason why you code it as a Singleton is for the global access. Just call it a global object then.

A Pool ?
(esp if you know how about the instance count early, but want to encapsulate some of the behaviour of constructing / destroying)

This does not sound like a singleton to me, it sounds like a regular class that always has at least one instance. Calling this a singleton, and writing the code as though it was one (eg. private static MySingleton instance = new MySingleton();) is confusing - decouple the "always present" instance from your class definition somehow. Make it clear in your implementation that this is a normal class that just happens to always have at least 1 instance around.

You could create a default instance getter.
private TheClass defaultInstance;
public Default{ get{ return defaultInstance??(defaultInstance = new TheClass());}

Related

Why things are so different in a driver class ("static void main") and a class definition?

I know some of the terms I use are confusing. To clarify, a driver class is basically one built on a class definition (starting with public class...) but is a method itself with the header public static void main (String args[]).
The point of this post is to resolve my serious confusion. (I am a beginner in programming)
to me, since a driver class is a method, all it does is to implement itself. But things kinda turn out to be the opposite . For example:
to implement a constructor in a driver class, you simply put down the constructor heading, like public Rectangle(), with its name being the same as that of the class. but in a class definition, to creat a object/ implement a constructor, you also have to write down happen inside that constructor, so you use the expression "type name = new type name ()".
PS: I might have used some terms wrongly, correct me thanks. Or some concept
I'll try to answer this the best way that I can.
Let's look at each of the keywords in a "driver class method" and determine the meaning.
public - this method is publicly callable by a class outside of it
static - this method is callable WITHOUT an instance of the class. In Java, look at the Math class. You don't need to instantiate an instance of the Math class to use the sqrt function (Math m = New Math(); m.sqrt(25);), you can just use Math.sqrt(25).
void - this method returns nothing
main - name of the method
Now that we have that cleared up, let's ask ourselves why these things have to be here for a "driver class"
The Virtual Machine (the program that runs your custom programs) is hard coded to look for a method named main that is public and can also be called WITHOUT CREATING AN INSTANCE OF YOUR CLASS.
So this means that when your program first runs, there is no instance of it.
To counter this, you can either create all of your methods and properties as static (generally considered bad practice) OR you can create an instance of your own class inside of it's own entry method, and begin to call the non-static methods and properties that belong to the instance.
I hope this makes sense.

How to call a remoteObject method that is outside of my TitleWindow component on Flex?

I have a TitleWindow component. It allows me to save some data provided through 3 TextInput.
That data "fills" a DropDownList which is in another TitleWindow component, not inside the original one.
How can I call the remoteObject method that fills (or refresh) my DropDownList?
Any ideas will be appreciated!
You can simply use a Singleton as a model if you'd like, this will allow you to share data, but beware keep data only that needs to be shared in here or it will just become a global nightmare.
Using a singleton means you'll have a class that you can only ever have one instance of. If you put properties in that class any time you reference it it will be the same memory throughout the application execution.
http://blog.pixelbreaker.com/actionscript-3-0/as30-better-singletons
Marking the singleton class or individual properties as Bindable will make it so you can watch for the changes and call a function.
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_8.html
Putting this together you have something like this:
[Singleton.as]
package
{
[Bindable]
public class Singleton
{
public var myListData:Array;
public static var instance:Singleton;
public static function getInstance():Singleton
{
if( instance == null ) instance = new Singleton( new SingletonEnforcer() );
return instance;
}
public function Singleton( pvt:SingletonEnforcer )
{
// init class
}
}
}
internal class SingletonEnforcer{}
Somewhere else you want to get a handle on this
[MyTitleWindow.as]
var instance:Singleton = Singleton.getInstance();
instance.myListData = [1,2,3];
[MyTitleWindowWithAList]
var instance:Singleton = Singleton.getInstance();
BindingUtils.bindSetter(funcUpdateList, instance, "myListData");
private function funcUpdateList(data:Object)
{
myList.dataProvider = data as Array;
}
Another option is to create an event that carries your data payload, dispatch that event from the first title window, and capture it, the problem with this is you have to register the listeners on the PopUpManager or SystemManager I believe because the TitleWindow's aren't direct children of the Application I believe.
Singletons are a bad idea and you should not get in the habit of using them. Instead, just dispatch an event from the View and catch it from something else that has access to your Service object.
Note that your Service should not be part and parcel of any View--the responsibility of a View is displaying data and capturing requests from the user to change the data, not communicating with a server.
For examples of an application written with this pattern in mind, check out
[Refactoring with Mate] (http://www.developria.com/2010/05/refactoring-with-mate.html) - The example has View source enabled
The same application done with RobotLegs - again, View Source is enabled.
Note that these are written against some popular frameworks, but they are written in such a way that you can easily replace that framework code with something else, even your own code.
For reference, here is the naiive implementation, where the service layer is being called directly in the Views. You couldn't call a different service without changing the Views, though the use of the static service means you could use it from elsewhere.
That static usage survived into the later examples, though today I would never write something depending on a globally accessible object. In part this is because I discovered Test Driven Development, and it is impossible to replace the "real" static object with an object that lets you isolate what you are testing. However, the fact that most of the code in the 2 "better" examples is insulated from that static object means that it is trivial to replace it with one that is provided some other way.
The lesson here is if you're going to use static, global objects, lock them away behind as much abstraction as you can. But avoid them if you're at all interested in best practice. Note that a Singleton is a static global object of the worst kind.

Is there a way to access entry point class object from other classes of the app?

Just wonder if I can reference entry point object from any place in the app? Is it maybe assigned to some global object, like stage is for example?
Currently I use static methods and variables, but this breaks encapsulation.
If someObject is in display list, then you have a someObject.root reference which is what you are looking for. If you remove someObject from display list, you loose that reference.
My answer is no, there is no direct way to access entry object, and there shouldn't be: that's what incapsulation is about. Accessing something globally is pretty much AS1 way. When you access main instance by implicitly referencing MainClass, you make parts of your application tightly coupled, which is generally bad.
However, if you do need to have it, you may choose from several options.
Use static var: MainClass.instance
Use singletone-like access through MainClass.getInstance()
Create a package-level variable or a package level getter method
I would choose the latter.
package com.smth.application
{
public var mainObject:MainClass;
}
// in main app
package com.smth.application
{
public function MainClass()
{
mainObject = this;
}
}
It may look somewhat similar to static acces, but I think this way your code will retain some flexibility.
stage is a reference to the top level of your application, which you can access though any display object that is on the display tree as myDisplayObject.stage. When using a custom document class, it will be the first child (index 0) of stage, unless you manually force something else into the 0 index as Bakapii says.

AS3 How do you access an instance of a class from anywhere?

I currently pass a reference to my model through the constructor to any class that needs it in my simple mvc pattern, this can get annoying at times when it starts to go deeper.
How do Classes such as LoadMax allow you from anywhere to simple import the class, and do something like addChild(LoaderMax.getContent("bg"));? Replicating this should surely be a good way to have my model work, without the complexity of big frameworks?
Statics are your friend
As previous answers have noted, TweenLite/Max etc. makes heavy use of static members to get work done. This is exactly like the Math class, for example, and can be a very convenient design pattern. You have global access to the class, and that can definitely alleviate the issue of getting access to variables through deeply nested classes.
Statics are the enemy
Statics, however, bring certain problems to the table. Most importantly, they tend to reduce flexibility and modularity of classes through the often unnecessary addition of tightly coupled relationships. It's a bit like pouring concrete over your application. It does work, but changing behavior becomes difficult as project features change.
Static members != instance members
Note, very clearly, that a static member "belongs" to the class itself, and not an instance of that class. Static members have no access to instance members. This causes troubles when you want to mix these members up in logic. You tend to have to make everything static (the so-called "static-cling" effect). Static patterns are often argued to be argued to be "anti" object-oriented, for precisely this reason. Once you build a structure on a static pattern you tend to lose many of the principles that makes OOD powerful.
In small does, they're pretty nice
That all being said - TweenLite is a great example of a static pattern that is totally appropriate - its a utility package, one that logic is not dependent on. And that should probably be how you leverage statics, too.
To reduce reliance on statics, or even global vars, it does often mean writing more code, but the flexibility in app structure gained is often quite worth it. #Marty_Wallace has a pretty good solution imo.
Demeter and the Paperboy
Finally, I'll just mention the Law of Demeter, or the Principle of Least Knowledge, and the related Paperboy and the Wallet example, which is often pointed to in discussions of statics:
Each unit should have only limited knowledge about other units: only
units "closely" related to the current
unit.
Each unit should only talk to its friends; don't talk to strangers.
Only talk to your immediate friends.
Hopefully that sheds a little bit of light on a fairly complicated and not-often obvious issue.
This is done using the static namespace, however I discourage the use of this.
package
{
public class Main
{
public static function sayHell():void
{
trace("hello!");
}
}
}
You can now call sayHello() like this from anywhere in the application (assuming you've imported the class).
Main.sayHello();
Another thing you can do (to make the entire class accessible from within the application) is create a static property that refers to the class itself:
package
{
public class Something
{
public static var instance:Something;
public function Something()
{
instance = this;
}
public function someFunction():void
{
trace('hello!');
}
}
}
Which you can now use like so:
Something.instance.someFunction();
The only thing to note here is that you need to create an instance of Something for this to work to call the constructor and define instance.
What I would do
Create a base class for all objects in your application
Create a manager class that takes care of these objects
Create a setter within your base class to define the manager
Here's an example:
Base
package
{
public class Base extends Object
{
private var _manager:Manager;
public function set manager(m:Manager):void
{
_manager = m;
init();
}
protected function init():void
{
manager.someFunction();
}
public function get manager():Manager{ return _manager; }
}
}
Manager
package
{
public class Manager extends Object
{
public function someFunction():void
{
trace('hello!');
}
}
}
Now anything that extends Base will have access to anything held in Manager via the manager getter property. All you need to do is make sure you define the manager, which is easily achieved from within anything that extends Base like so:
var something:SomeExtendingClass = new SomeExtendingClass();
something.manager = manager;
The example you gave is just a static method, but to answer your question about a global instance of a class:
package myPackage
{
public var globalVariable:MyClass = new MyClass();
}
You can access it with:
import myPackage.globalVariable;
trace(globalVariable);
I think you have to rethink in which way you want to name your classes.
You can instantiate whatever class you want, at run-time, but to access a instance by name, you have to make changes in your structure. For example, the getContent() function you mentioned in LoaderMax, all it does is to search in an array for the given loader that matchs the name, among other things. You can read the name variable comment for a description.
A name that you use to identify the loader instance. This name can be fed to the getLoader() or getContent() methods or traced at any time. Each loader's name should be unique. If you don't define one, a unique name will be created automatically, like "loader21".
So in this system, you have to name every single member (loaders in this case) if you want to be able to search them. Because if I call getClassInstance("myinstance"), what is "myinstance" representing? Where should I name it?
That said, if you want to do it for DisplayObjects only, you can use getChildByName. But again, you have to name every DisplayObject (just set the name variable).
Hope this helps.

Different Singleton instances with JUnit tests

I have a standalone singleton which successfully passes the test. But with a group of tests this fails since once a singleton is defined it does not allow to reset the instance.
Any ideas about how to go about this?
I assume you have a private static field within your singleton class to store the initialized instance.
If you do not want to modify your code, you can define a teardown method which run after every test, and in this method you set this static field to null via reflection as seen here.
Don't use a singleton.
Specifically, the only difference between a singleton and a global variable is that the singleton tries to enforce a single instance (by making the constructor private, for example).
Instead, make the constructor public and write tests using new instances. In your actual program, use getInstance() to get the canonical global instance (or use an IOC container).
And remember that singletons are pathological liars.
If you're still too comfortable with the idea of a Singleton, instead of making the constructor public you can add a public (and static) factory method to create instances in a way that can't be used by accident, e.g.:
public static MyClass TEST_CreateInstance() {
return new MyClass();
}
Spring provides the DirtiesContext annotation for this particular use case where you need new instances of the singleton beans for each testcase. It basically creates a new application context for each testcase/testclass which has this annotation applied.
You can add a method to destroy the singleton, for example destroyMe(); where you deinitialize everything and set the instance of the singleton to null.
public void destroyMe(){
this.instance = null;
//-- other stuff to turn it off.
}
I will leave synchronization problems though ;)
But why do you need to re-initialize your singleton for each test? It should not differ based on the concept of the singleton.
I highly recommend moving away from Singletons as a design pattern, and using Singleton as a scope (Dependency Injection). This would simply make your problem go away.
But assuming you are stuck in the world of Singletons, then you have a few options depending on if you are testing the Singleton or the dependency.
If you are testing the dependant item then you can mock the Singleton using PowerMock and JMockIt. See my previous post about mocking Runtime.getRuntime for instructions on how to go about this.
If you are testing the Singleton then you need to relax the rules on construction, or give the Singleton a "Reset" method.
generally beware of singletons, most often they are evil, bad design and tend to represent big yucky global variables (which is bad for maintenance).
still to get tests in place first you can do:
static setInstance(...){ //package visibility or in difficult cases you have to use public
instance = ...;
}
as said this is more a workaround. so get first tests place, but then refactor away from singleton pattern.
Singleton instance needs to be passed to SUT by test itself - that way you create singleton (and destroy) for each test. Adopting IoC and mocking framework, like Mockito, would render this approach almost trivial.
Very late to the party here, but for anyone looking for an answer, in case you don't want / cannot modify the code.
#BeforeEach
public void setup() {
object = Singleton.getInstance();
}
#AfterEach
public void after() {
// cleaning the singleton instance
ReflectionTestUtils.setField(object , "internal_object_name", null);
}
your Singleton class should be something like this:
public final class Singleton {
private static Singleton internal_object_name;
private Singleton (){}
public static Singleton getInstance() {
if (object == null)
return new Singleton();
else
return internal_object_name;
}