singleton class in Flex - apache-flex

I know singleton class is not supporting in Flex.Because it does not access private constructor.
But i want to make a class is singleton class. Please anyone can explain with example.
Thanks,
Ravi

A singleton is a class of which only one instance will be created. This instance will be shared by all other code in the program.
A singleton in the strictest sense is not supported in ActionScript because a constructor cannot be marked private. Consequently, additional instances of the class could be created elsewhere in the program. With the following trick, you can ensure that the constructor is only called by the singleton class itself:
package {
public final class Singleton {
private static var instance:Singleton = new Singleton();
public function Singleton() {
if( Singleton.instance ) {
throw new Error(
"Singleton and can only be accessed through Singleton.getInstance()" );
}
}
public static function getInstance():Singleton {
return Singleton.instance;
}
}
}

Related

Dependency injection in my singleton class .NET Core

I'm having trouble injecting the dependency I pass into the constructor of my Asegurador class.
When I want to instantiate, _instance = new Asegurador(); I don't have the parameter required by the constructor (IGeneralRepository), how can I solve this problem?
Note that my Asegurador class is a singleton.
private Asegurador(IGeneralRepository generalRepository)
{
_token = GetTokenAsync().Result;
_repository = generalRepository;
}
public static Asegurador Instance
{
get
{
if (_instance == null)
{
_local = System.Environment.GetEnvironmentVariable("SEGUROS_LOCAL") ?? "local";
_instance = new Asegurador();
}
return _instance;
}
}
When using a DI container you can (and should) let it take care of handling the Lifetime of a dependency.
.Net core's dependency injection lets you define 3 different lifetimes for your services (Docs):
Transient: a transient service is recreated each time it is injected
Scoped: a scoped service is created once for each request
Singleton: a singleton is created once in the whole application lifetime.
The best approach to achieve what you are trying to do is the following:
Amend your Asegurador class so that it has a public constructor and get rid of the static Instance property
public class Asegurador {
public Asegurador(IGeneralRepository generalRepository)
{
_token = GetTokenAsync().Result; //I know too few about it but I would try to pass it as a dependency as well
_repository = generalRepository;
}
}
instead of calling Asegurador.Instance inject the dependency in the client class
public class IUseTheAsegurador {
private Asegurador _asegurador;
public IUseTheAsegurador(Asegurador asegurador)
{
_asegurador = asegurador;
}
}
Register all in the DI in your Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<Asegurador>();
services.AddScoped<IUseAsegurador>(); //This can be Singleton or Transient as well, depending on your needs
...
}
I (a lot of people actually :D) prefer this approach because it leaves the responsability of guaranteeing a single instance to the DI and also because lets you write unit tests for the client class (IUseTheAsegurador in the example) in an easier way.

Responsibility of object creation within class

This might sound like a noob question.
class MyClass
{
public List<MyObjects> myObjects;
public MyClass()
{
//...
}
}
class UserClass
{
public void SomeFunction()
{
MyClass obj = new MyClass();
//Should this belong in constructor of MyClass?
obj.myObjects = new List<MyObjects>;
//Should 'SomeFunction' initialize obj.myObjects before using it, or
//should it assume it has been initialized and just use it?
obj.myObjects.Add(..);
}
}
Who is responsible for creation / initialization of MyClass.myObjects, when the default constructor is invoked?
Constructor of MyClass.
User of MyClass.
In general, the constructor of a class should do all work necessary for that class to be in a usable state. In your case here, you should probably provide an accessor method for myObjects. The principles of OOP say to encapsulate data. That means that myObjects should be private. You should only have access to it via accessor methods. By doing that, then you can construct the object and lazily create the list via the accessor method when it is actually needed.
Here is a wiki article dealing with Constructors. It mentions that a properly written constructor will leave the object in a valid state.
EDIT: Encapsulated myObjects with lazy initialization (Note I am assuming C# since your code sample looks kind of like that)
class MyClass
{
private List<MyObjects> myObjects;
public MyClass()
{
//...
}
public void Add(MyObject object)
{
MyObjects.Add(object);
}
private List<MyObjects> MyObjects
{
get
{
if (myObjects == null)
{
myObjects = new List<MyObject>();
}
return myObjects;
}
}
}

Is this a true implementation of Singleton Pattern?

All tutorials I've read till now about Singleton pattern were as below :
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
but I already have a class in a assembly that I need to just have one instance of it during application lifetime . I don't know how to use pattern mentioned above .
for example suppose there is a class X in dll named Y . is the code below correct :
public sealed class Singleton
{
private static readonly Y.X instance = new Y.X();
private Singleton(){}
public static Y.X Instance
{
get
{
return instance;
}
}
}
is this a true singleton ? if not , what is a correct way to handle this situation ?
No its not the singleton pattern. The fact that you are calling new Y.X() means anyone can call it. This does not specifically disallow new instances of Y.X()
However the code is okay if you need to make sure that you refer to only one instance of Y.X in your application. Then you can get it by calling Singleton.Instance.
This is in fact the Factory pattern (A class dedicated to creating objects), and I would suggest you call the class XFactory or something similar, instead of singleton.
I would use something like :
public static class Singleton<T>
where T : new()
{
private static readonly Lazy<T> instance = new Lazy<T>();
public static T Instance
{
get
{
return instance.Value;
}
}
}
The idea is to use Generics in order to allow specify any type as type parameter.
The lazy is just an improvement to instantiate the actual instance of the object.
Please note that this won't disallow creating instances of T directly...

Hadoop Map output IOException when emitting subclass of a class defined in Configuration as an ouput

I have 3 simple classes:
public abstract class Container implements WritableComparable<Container> {} //empty
public class WeightedEdge extends Container { ... }
public class NodeWeightContainer extends Container { ... }
The Map phase was configured as such
JobConf createGraphPConf = new JobConf(new Configuration());
Job job = new Job(createGraphPConf);
...
createGraphPConf.setMapOutputValueClass(Container.class);
However I am receiving this error:
java.io.IOException: Type mismatch in value from map: expected org.hadoop.test.data.util.Container, recieved org.hadoop.test.data.WeightedEdge
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:1018)
at org.apache.hadoop.mapred.MapTask$OldOutputCollector.collect(MapTask.java:591)
at org.hadoop.test.map.CreateGPMap.map(CreateGPMap.java:33)
at org.hadoop.test.map.CreateGPMap.map(CreateGPMap.java:19)
at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:50)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:435)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:371)
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:210)
Why I can't return a subclass of a class that was defined in the configuration? Is there a way around it? The problem is that my Map phase has to emit two distinct object types.
You can not return a subclass of a class that was defined in the configuration because Hadoop explicitly checks class type specified in setMapOutputValueClass and the type it receives from Mappers.
It does so because it needs to serialize/deserialize objects you emit from mappers. When it performs deserialization it creates new object of type that is specified in setMapOutputValueClass call and then uses methods of WriteableComparable interface to fill newly created object with data.
To be able to emit different object types you may define container non-abstract class and place actual object and its type identifier inside
public enum ELEM_TYPE { WE, WECONTAINER }
public class Container implements WritableComparable<Container>
{
ELEM_TYPE type; //actual element type -
// WeightedEdge or NodeWeightContainer
object value;
//WritableComparable implementation
// that casts value to the appropriate type
}
public class WeightedEdge { ... }
public class NodeWeightContainer { ... }
I faced the same problem today. There is a Writable class org.apache.hadoop.io.GenericWritable which can be used to address this problem. You need to extend the class and implement an abstract method:
public class Container extends GenericWritable {
private static Class[] CLASSES = {
WeightedEdge.class,
NodeWeightContainer.class,
};
protected Class[] getTypes() {
return CLASSES;
}
}
public class WeightedEdge implemets Writable {...}
public class NodeWeightContainer implements Writable {...}
Now you can use the class Container as the output value type of your mapper.
Important: Your actual map output classes (WeightedEdge and NodeWeightContainer) must implement the Writable interface.

How do I Inject Dependencies with Ninject, where instances are deserialised from json

This is my first try using DI, I've chosen ninject for it's reportedly easy learning curve, and have this question.
I'm creating objects like this:
var registrants = JsonConvert.DeserializeObject<List<Registrant>>(input);
I currently have this constructor for Registrant
[Inject]
public Registrant(IMemberRepository memberRepository)
{
_memberRepository = memberRepository;
}
What is the best way to have the repository dependency be injected into the deserialized object(s) using Ninject?
You can't use constructor injection with objects that are not created by Ninject (e.g. deserialized objects). But you can use property injection. Just call kernel.Inject(obj)
One question that remains is why you want to inject those objects. Normally, you don't want to use depedency injection on data container objects. In a proper design they don't have any dependency on services. The operations that need to be done on the services are done by the owner of the data container objects. I recommend to consider a refactoring of your design.
Assuming you're using Ninject V2, and you're using it in the context of an ASP.NET app, you should be using Ninject.Web to do the hookups.
Then you set up a Global class with the Factory Method support hooked in:
public class Global : NinjectHttpApplication
{
protected override Ninject.IKernel CreateKernel()
{
var kernel = new StandardKernel( new Module() );
kernel.Components.Add( new FuncModule( ) );
return kernel;
}
}
that registers the module that will Bind IMemberRepository to something:
public class Module : NinjectModule
{
public override void Load()
{
Bind<IMemberRepository>().To<MemberRepository>();
}
}
and the page wires up like this:
public class ThePage : PageBase
{
readonly Func<Registrant> _createRegistrant;
public ThePage( Func<Registrant> createRegistrant )
{
_createRegistrant = createRegistrant;
}
private void OnCreateRegistrant()
{
var newRegistrant = _createRegistrant();
}
}
NB not 100% sure if constructor injection is supported for Web Forms pages or wheter the above needs to drop to property injection... anyone?
(assuming the classes you have are as follows:)
public class MemberRepository : IMemberRepository
{
}
public interface IMemberRepository
{
}
public class Registrant
{
private readonly IMemberRepository _memberRepository;
public Registrant( IMemberRepository memberRepository )
{
_memberRepository = memberRepository;
}
}

Resources