Not quite a Singleton
I'm using ActionScript3 to develop a Data Access Layer for an a开发者_如何学运维pplication another developer is working on in my team. One of the objects, lets call it User
is expensive to construct. Each user has a unique ID number so I can tell if they've been created before or not, and all User
objects are stored in an array somewhere else.
I want to be able to restrict it so that there can be only once instance of a User
per ID. I.E. each user has to be unique, and requests for an already constructed User
should receive the pre-constructed User
.
If I was using a sane, well-designed language I would simple make it a private constructor and force all requests for the object to go through a function that cached things. But flash doesn't allow private constructors (only public and internal, neither of which will work). How can I achieve this?
If you want to do the private construtor then you can achieve this like this:
package somepackage {
public class User {
public function User(SingletonEnforcer s):void {
if (s == null)
throw new Exception("Sorry mate!!!");
}
public static GetUserWithId(id:String):User {
//user with this id exists then return it.
//create a new user, initialize it, cache it and return
}
}
}
class SingletonEnforcer {
//this is only visible to this class (User).
}
You could use a dictionary to store user ids mapped to User instances. This way you could check to see if there was already an existing user before creating a new one. Here is some pseudo code:
public class UserLookup()
{
var _lookup:Dictionary = new Dictionary();
function getUser( id:int ):User
{
if( _lookup[id] ) {
return _lookup[id]
} else {
var user = new User( id );
_lookup[ id ] = user;
return user;
}
}
}
精彩评论