Singleton Pattern problem

I try to be a good ActionScripter OO using the Singleton to have the control panel for an application.
Here is the code and it works fine:


the package com.gh {}

[Bindable]
public class SystemVars {}

private static var _instance:SystemVars;
private var _serverIP:String = "10.0.0.228";
private var _serverPort:int = 7700;

public void SystemVars (be: SingletonEnforcer): void {}
}

Public Shared function getInstance (): {SystemVars}
If (!.) SystemVars._instance) {}
SystemVars._instance = new SystemVars (new SingletonEnforcer());
}
Return SystemVars._instance;
}

public function get Ip_serveur (): String {}
Return _serverIP;
}

public function set Ip_serveur (serverIP:String): void {}
_serverIP = serverIP;
}

public function get serverPort (): int {}
Return _serverPort;
}

public function set serverPort (serverPort:int): void {}
_serverPort = serverPort;
}
}
}

Class SingletonEnforcer {}
public void SingletonEnforcer (): void {}
return;
}
}


The problem comes when I want to use the Singleton Pattern have variables defined in a database using a HTTPService:


the package com.gh {}
Import mx.rpc.http.HTTPService;
Import mx.rpc.events.ResultEvent;


[Bindable]
public class SystemVars {}

private static var _instance:SystemVars;
private var _serverIP:String;
private var _serverPort:int;
private var _httpService:HTTPService;

public void SystemVars (be: SingletonEnforcer): void {}
}

Public Shared function getInstance (): {SystemVars}
If (!.) SystemVars._instance) {}
SystemVars._instance = new SystemVars (new SingletonEnforcer());
SystemVars._instance.setVars ();
}
Return SystemVars._instance;
}

public function get Ip_serveur (): String {}
Return _serverIP;
}

public function set Ip_serveur (serverIP:String): void {}
_serverIP = serverIP;
}

public function get serverPort (): int {}
Return _serverPort;
}

public function set serverPort (serverPort:int): void {}
_serverPort = serverPort;
}

private function setVars (): void {}
_httpService = new HTTPService();
_httpService.URL = "" http://10.0.0.228/data/system_vars.php "; "
_httpService.ResultFormat = HTTPService.RESULT_FORMAT_E4X;
_httpService.addEventListener (ResultEvent.RESULT, httpServiceResultHandler);
_httpService.send ();
}

private function httpServiceResultHandler (event: ResultEvent): void {}
_serverIP = string (event.result.serverIP);
_serverPort = int (event.result.serverPort);
}

}
}

Class SingletonEnforcer {}
public void SingletonEnforcer (): void {}
return;
}
}


This works very well, with the exception of the values are null until the HTTPService returns a result.
What I want to do, do not return the instance until there is a result, it's is it still possible?

Or do I have to use a different approach?

Analysis of Tracy to the situation above is accurate.

Well that isn't ideal, a way to handle this would be to use a reminder. Basically, instead of returning a reference to your singleton directly, need you a reminder that expects a single argument, which will be a reference to your singleton. If the service is already back with the results, you simply call this callback immediately. Otherwise, you add to a table (since getInstance can be called several times before the service returned), then you call these reminders in your service result handler. Below are the changes you would make to your code:

private var _callbacks:Array = [];

public static void getInstance(onInit:Function):void {}
If (!.) SystemVars._instance) {}
SystemVars._instance = new SystemVars (new SingletonEnforcer());
SystemVars._instance.setVars ();
}
of other if(!_serverIP) / / we are still waiting on a result
_callbacks.push (OnInit);
on the other
onInit (SystemVars._instance);
}

private function httpServiceResultHandler (event: ResultEvent): void {}
_serverIP = string (event.result.serverIP);
_serverPort = int (event.result.serverPort);

for (var i: int = 0; i< _callbacks.length;="" i++)="">
var fn:Function = _callbacks ;
FN (this);
}

_callbacks = null; We're done with it, so the memory
}

Tags: Flex

Similar Questions

  • Using the Singleton Pattern to keep the values of the previous variables?

    Is it possible using ExtendScript to retain the previous property, same value once it has been updated by the user? I know after effects update images expressions, but I believe that the values of script must be able to persist. This kind of thing is possible with ExtendScript?

    I think something like this should be achievable using a singleton as a model, but so far I've succumbed. Here's what I've tried so far:

    instance of the var;

    Check the value of the current instance

    Alert (GetInstance () .value);

    Check if the instance has a value, if this is not the case assign one, otherwise return the current value

    function getInstance() {}

    {if(!instance)}

    instance = createInstance();

    }

    return instance;

    } //End getInstance

    Create the new object with a value and return it

    function createInstance() {}

    var object = new Object (mySel.property("Effects") ("Transform") .property .property (1));

    Returns the object;

    } //End createInstance

    Or, if singletons are the wrong approach is there any type of storage mechanism that can be called in ExtendScript to write values?

    Thank you!

    I don't know (which means no there are not), but maybe your problem could be simplified.

    Your best chance would be to want to want to know if the property is changed at all, in which case you can use p.isModified.

    But if you want to know if it has been modified since the last change, then its a different story. Properties objects cannot be instantiated on their own, they are related to the actual properties in layers and cannot be "frozen".

    Brutal way:

    If the property is suspected of having a set of keys, you would be better of caching the stream of values in a table;

    Otherwise be cached keys (still many things to do... times, values, tweens) and the expression, but then comparing two States can be uncomfortable.

    .. for every p in your effect.

    I hope that you will get a better answer

    Xavier.

  • repeat pattern problem

    Hello community!

    I have a problem with a template / original model. matter of fact, I've had this problem several times:

    I create a pattern. the model looks good, just cool. I switch back to my real surface Board graph/layer/drawing. I create a box and fill it with the model, let's say in the middle of the artboard. all of a sudden the boss takes its source in the Middle, on the side or I don't know where... and for some reason I can't give him originally that I want... ? ! How can I set a point of origin for the model without having to turn it into a path or such?

    If the patten was really bad I have it and stuffed it into a document InDesign, placed as needed and make print that way.

    But there must be an easier way?

    Waiting for relief,

    Thank you!

    I added these shots for orientation.

    the white part down was taken from the top and jostled at the end of the repetition of reason o_O

    (the image on the right is as it should be and how it looked like in the model creation tool, the image on the left is how the model is out)

    raster_fault.JPGraster_should_be.JPG

    Origin of the sequence is positioned at the origin of the leaders; (x = 0 / y = 0). To control its proximity with the purpose, align the top left point of the object to the origin of the rule, or vice versa. To make it stick anywhere else, you move the object, expand the fill of the object.

  • My compensation filter does not work in Cs6: Seamless pattern problems

    Hi all.

    Im trying to create a seamless model. by using many layers.

    Im going to filter/other/offset /, adding vertical or horizontal dimensions such as 2953px (image size is 2953px x 2953px). and by checking the box "wrap autour.

    But it does not work and is culture off loads of the layer, not transparent at all.

    I tried with another layer, and the same thing happens.

    I have "revealed all" and shows nothing. I tried to remove the transparent noise pixels around the layer, I am trying to wrap.

    & I also selected all & then cropped the image, but it is always the case.

    I googled until my heart's content, but found no other idea on how to solve. Any ideas?

    All my layers are brushes I created and used so many transparent textures. But it would be a problem if I tried all this would?

    Thanks in advance.

    "" Photoshop is not a "tool of compensation", as I know not, but a filter called Offset.

    You can try cropping the image to the canvas size (select > all, Image > Crop) before applying the offset?

  • Pattern Singleton MAF 2.2.0

    Hello

    I have a change in behavior after upgrade to 2.2.0 MAF. I'm not sure if this is intentional or a bug. For me, looks like a bug because it is at odds with the singleton design pattern and behavior change does occur when the application is disabled, and then press it again.

    Basically, I have a class in the ApplicationController which has been implemented in the singleton design pattern. The instance of this class (singleton) behaves as a singleton and is used by all the features. So MAF 2.1.3 which has worked. As MAF 2.2.0 instance behaves as a singleton until the application is disabled and then press it again.

    Here's the scenario:

    (1) start the application = > the singleton is created

    (2) go to any device = > the singleton is always the same instance.

    (3) turn off the app

    (4) to activate the soft

    (5) the original instance (singleton) is always available in the ApplicationLifeCycleListenerImpl as we like the functionality of the application in when he was disabled and enabled

    (6) go to any other feature = > now I have a new instance of the class that implements the singleton pattern (I did several instances)

    Everyone knows anything of this kind? I'm running on iOS.

    Kind regards

    Majdi Jaqaman

    Hello

    This has been fixed in 2.2.1 MAF.

    Kind regards

    Majdi Jaqaman

  • SIngleton and BlackBerry - need help

    Hi all

    I was wondering:

    If I want to make sure only one instance of my application is running - should I use the Singleton Pattern or not only the operating system of BB takes care of this?

    If I start the emulator once it, be it downloaded whenever I'll re - compile and rerun? (I mean the first round)

    My application is a PhoneListener application with a GUI, nothing complicated.

    Thank you!

    Not sure I understand the question.

    When you run the emulator, your application is is started during the boot process (if you have set the option to auto-start your project), or it is not. Each restart of the Simulator is basically the same as the device to start.

    If you do not have the autostart property set, then your application starts when you click the icon. If you exit the application and click on the new icon, your application is restarted.

    You can keep your application running in the background you override the close() method in your top-level window and perform a "requestbackground()". Then your application is reinstated through the method "activate()' rather than being rebooted.

    All this is covered faily well in the development of RIM software guide and the sample applications provided with the JDE.

  • Approach to singleton for screens

    Hello

    I would like to know if it is advisable to use a singleton pattern when you push the screen on the stack.

    For example:

    package com.xyz.mobile;

    Import net.rim.device.api.ui.container.MainScreen;

    SerializableAttribute public class EntryScreen extends form {}

    Private Shared EntryScreen thisInstance = null;
       
    private EntryScreen() {}
    Super();
    TODO initialize the fields here
    }
       
    public static getInstance() {} EntryScreen
    {if(thisInstance==null)}
    thisInstance = new EntryScreen();
    }
    Return thisInstance;
    }
       
    }

    Now in my application UI I would call:

    pushScreen (EntryScreen.getInstance ());

    The advantage I see is I would not re - initialize my fields whenever I want to push the EntryScreen in the stack. Is this recommended practice. ? Kindly guide me with this.

    Thanking you,

    Kind regards

    S.A.Norton Stanley

    If you have a reference to the screen, it will not change.

    You can do
    YourScreen yourScreen = new YourScreen();
    pushScreen (yourScreen);
    popScreen (yourScreen);
    pushScreen (yourScreen);
    etc.

  • Singleton vs normal/global variable

    Hi just been looking intot he singleton pattern. WHY should I use this template to contain the variables accessible to other sovereign wealth funds throughout the project when I can just keep in the film container and access as you wish.

    Is there an advantage as optimization, security, usability etc...

    I'll post a question re: how to access a varibale in a mc parent except if answered here too as it is in the same category.

    It is better to go to a varibale in the parent uses

    1 MovieClip (parent.parent) .variableTargeted

    OR

    import com.parentAsDocument;

    Then navigate to the variable

    Thanks in advance

    (btw. I've never seen this in tutorials anywhere - and I've read for years - I missing something here or is - something advanced programmers don't know because they read advanced books?)

    If I need to use global variables - I'll probably use public static properties (variables) and methods in a special class that is designed to provide the values of these variables (or the features of the static methods) for the entire application. Any object making the reference to this class will be able to read/write these values.

    You are already familiar with static properties. For example when you add event listeners you write:

    mc.addEventListener (Event.ENTER_FRAME, handler);

    ENTER_FRAME is a static variable (and also a constant) which is accessible to ANY other object in the application around the WORLD.

    On the issue of container, I think you're talking about higher-level (timeline or document class) code. If my impressions are correct - no, I would never declare static properties or methods for the use of the application to scale. As I said, I would create a class special and this feature delegation to the and then tap other classes if necessary top.

    Frankly, I would never use timeline for anything unless someone puts a gun against my head (or hands a lot of money). In fact I avoid using IDE Flash quite like a plague. I mean that for one purpose - timeline coding is treacherous (and, oddly, more complicated than the use of the class) and encourage people is not to think of OBJECT-oriented way. The main disadvantage is that developers often assume that the chronology provides a kind of guarantees and the decorum and thus developers spend hurt little time thinking about the architecture of application in a more abstract way.

    I highly suggest if you consider excel programming skills to give up the chronology of coding as soon as possible (including the use of the Flash altogether) and move toward Flash Builder or any other environment. Benefits are awsome and you will never want to go back to the timeline.

    If you want to me - I'll give you a more concrete example of how I would approach implementation of the static aspects of the classes.

  • Basic image - launch actor actor

    I have a problem, I have a core "player". When we use the actor 'launch' to "Actor Open Core front panel", it is possible to know if already "basic player" is actor started and advanced. I call several times to "Launch player", a "core of the actor" whenever the call is made, the place opens, I want to have a single 'base player' and should be open, make the front of the façade. Is it possible?

    The answer is no - the AF is designed to run multiple copies of the process. If you want to use a single copy (essentially a variation on the singleton pattern, which is a term that you can search), you will need to code yourself.

    A simple solution is to use a non-reentrant VI. The first call (there is a primitive that returns this) launch the actor and put his enqueuer into a knot of registry or feedback shift If the first call is F, take the enqueuer leave feedback node and send a message 'open' to the actor or simply return the enqueuer.

  • Application when setting App crashes

    So, I'm working on this example; https://github.com/thurberdog/BlackBerryCascades/tree/master/pushCollector

    I wrote a function and added to app.cpp;

    void App::registerToServer(QString apiURL, QUrl params)
    {
        QUrl serviceUrl = QUrl(apiURL);
        QByteArray postData;
        postData = params.encodedQuery();
    
        QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    
        networkManager->post(QNetworkRequest(serviceUrl),postData);
    
        // Connect to the reply finished signal.
        connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(httpFinished(QNetworkReply*)));
    }
    
    void App::httpFinished(QNetworkReply* reply)
    {
        qDebug() << "httpFinished called";
       // qDebug() << reply->readAll();
        int code = -1;
        QString description;
        QString returnCode;
    
        returnCode = reply->readAll();
        qDebug() << "RC: " + returnCode;
        if(returnCode.contains("rc=1001")){
            m_pushDAO.addTokenDB(getDevicePIN());
            showDialog(tr("Device Registration"), tr("Your device has been successfully registered!"));
            changeConnectionText("Connection Status: Connected!");
    
        } else if (returnCode == "rc=1002"){
            showDialog(tr("Device Registration"), tr("Unable to register your device. Please try again later. E1002"));
            changeConnectionText("Connection Status: Error E1002");
        } else if (returnCode == "rc=1003"){
            showDialog(tr("Device Registration"), tr("Your device has already been registered. Please login to your account online and remove you device. E1003"));
            changeConnectionText("Connection Status: E1003");
        } else if (returnCode == "rc=1004"){
            m_pushDAO.removeTokenDB();
            showDialog(tr("Device Unregistration"), tr("Your device has been unregistered."));
            changeConnectionText("Connection Status: Not Connected");
        } else if (returnCode == "rc=1005"){
            showDialog(tr("Device Unregistration"), tr("Unable to unregister from our servers. E1005"));
            changeConnectionText("Connection Status: Unable to unregister. E1005");
        }
    
        emit closeActivityDialog();
    
    }
    

    Now in the file Push.cpp, when I try to do;

    App m_app;
    
    m_app.registerToServer(etc etc)
    

    My plant app with the following:

    terminated SIGSEGV code=1 fltno=11
    

    Any help would be appreciated! I'm pretty new to this, so go easy

    Hello

    the problem is that you said m_app type App, but it has no value and so when you try to call your function, you get a SIGSEGV. If you know Java, it's like a NullPointerException.

    You need to pass a pointer to the object of your App in Push.cpp or allow to get one within the Push.cpp. One possibility is to use the Singleton pattern. See the Statemanager.hpp / Statemanager.cpp class in NfcTool for an example. You can just call YourClass-> getInstance() to get a pointer to the single instance of this class and then can call its functions/methods.

    https://github.com/BlackBerry/Cascades-community-samples/BLOB/master/NfcTool/src/StateManager.hpp

    Hope this helps

    Martin

  • How to implement a stack of screen "single instance".

    I'm looking to implement an application that accepts only a single instance of specific screens.  What is the best way to achieve this?  I have checked the documentation and can't seem to find anything that addresses this issue.

    The idea is similar to a singleton pattern...

    If (screen is nothing)

    {

    screen = new XYZScreen ();

    }

    return to display;

    If I already pushed my XYZScreen in the stack, using the pushScreen() method, I would like to get a handle to that instance, and they have to protest against the creation of another instance and add it also.  Also the memory problem, it makes more sense for the particular project that we are working on.

    I can't seem to find anything like "UiApplication.getUiApplication.getScreen ()" to get a reference to a particular screen already on the stack, or a 'Stack.moveScreenToTop () '.

    Suggestions, examples or links would be appreciated.

    You can use getActiveScreen() and getScreenBelow() in a loop to see if your display is already present in the stack to display.  If this is the case, then pop, and you then press it to remove it from its current position and make it visible.  If it is not on the stack, you can just push it.

    It works for you?

  • methods of a JavaFX application from another application

    Hallo.

    So, I did some work on JavaFX 2.0 integrating graphics into a program called Max/MSP. It is a kind of Visual language for handling the music. Among it's features is the ability to write your own classes java, extended by the MaxObject class and create the custom components in your Max Patches. I received a MaxObject to launch a JavaFX applications, so I know that this part can be done. Now, I need two programs to talk properly with each other.

    So, what I'm looking for is a pretty standard, reliable way to get ApplicationA, i.e. which launches application (and thusly can pass arguments by hand), to be able to transmit information in application B and vice versa. I'm assuming that someone else out there he wanted a JavaFX application to interface with another piece of java code. An Advisor on what should I look for in? Both applications are running on the same computer. And I hope my question is clear decently...
    -Jean

    Hey John,

    I would like to try some of the following to refine your question:
    * Put your launch within another thread code to see if that stops the problem of blocking
    * use a random value that is passed to your application instead of 42 so that you can tell if new instances are created, etc.
    call a different method for bang for your second call to the method just separate the flow to isolate your question

    Something like:

    public class MaxPart extends MaxObject {
    
        private boolean started;
        private Circles circles;
    
        public synchronized void bang()
        {
            if (!started)
            {
                outlet(0, "Starting Circles application...");
                started = true;
                new Thread()
                {
                    public void run()
                    {
                        Application.launch(Circles.class, null);
                        outlet(0, "Circles application launch completed");
                    }
                }.start();
    
                // you could do some synchronized blocking here to wait for the instance to be set, try just doing a
                // simple sleep for now and add synch in if it works
                try { Thread.sleep(2000); } catch (InterruptedException e) {};
    
                circles = Circles.instance;
                Double randomValue = Math.random();
                outlet(0, "Circles assigned random value: " + randomValue);
                circles.setValue(randomValue);
            }
            else
            {
                outlet(0, "Circles is already started, not starting another one");
            }
        }
    
        public void anotherBang()
        {
            outlet(0, "Circles random value was: " + circles.getValue());
        }
    }
    

    Either way, you mention that you want to use the Singleton pattern. You pretty much are already - the 'instance' is a singleton that gets the value once (when the Application is launched) and is then used in the world. There is nothing real magic of singletons.

    Also, just to let you know the 'main' method in your application of circles is not needed or used. The bang method directly calls the launch. You only need this main method if you want to run the standalone app of circles (which is still useful for testing).

    Hope that helps,
    zonski

    Did you find this answer useful? If so, please indicate as 'correct' or 'useful '?

  • What is the duration of A hurried event last?

    I'm looking for a technique of memory proposed by Adobe where if I want to save and share between components, I can encapsulate data in a custom event class.  The problem I have has to do with how long an event of a reshipment.  I have a component that I want to store and share data, so I wrap the data in an event class and address.  The component that I want to share the data with has not been instantiated yet until further in the life cycle of programs.  When this component is instantiated and a listener is created to intercept the event, the event will still exist and the data still pending?  If this is not the case, how can I get the first component data shared with a component that lives on the line?

    What you're missing is a data model that stores data and based user interface applications. You need to research the MVC architecture.

    The basic premise is this.

    The user interface interacts with the user to view the data from the model and update the model according to the user interactions, in General, what the user sees in the user interface is a representation of the data in the model no data which is held in the user interface. An example might be a series of sales figures. A user interface component can display data by using a datagrid control, while another part of the user interface may show pie chart or histogram, etc.. Interface components user refers not to the other, but show that what is stored in the model. In Flex, the user interface often used the data binding on the model, to get the needed to display data.

    The model is the basis of the application and the user interface is only there to view the model and for the user to update the model. The user interface and the model are separated.

    The model can be as simple as a class that can be accessed by all the user interface components. A popular way to access data from anywhere is the singleton pattern, which allows access to the data without declaring the class of the user interface.

    The final part of the MVC uses events to communicate changes to the user interface to the model. This is done using a controller, which captures the user interface events and updates the model according to what is happening in the UI.

    It's all a lot to take.

  • Sending events from instances of the class

    Hello
    I have problems with dispatching events from instances of class.
    In a simple MXML application, I added an event listener for a custom event.
    In accordance with the rules of good practice MVC, I have a template with a single instance (singleton pattern) class. This instance has no reference to my MXML component. When my model receives the data from the server, I want to send an event of this forum (which isn't in the displayList!). I could solve that problem with a model of the observer, but there is no way to any shipment of the event?
    Help much appreciated!
    Dany

    Hello Cesare,

    It works indeed! Thanks a lot for your help here!

    Dany

  • The appeal of Java DB stateful classes?

    Is it possible to call Java classes in the virtual machine JAVA DB? I often see static methods used with the only thread discussing this mention structures SQLData and STRUCT. I need a java class that would keep the State and have a lifespan of several calls to PL/SQL. You can use the singleton pattern in the comic book? I had the image of the documentation of classloader that the classpath would be unique per session so that is an option?

    I'm not sure I understand the question, but have you tried to create a class with static variables to contain references to your classes with State? According to your requirement, the static variable could be a hash table storing an arbitrary number of objects.

    The content of static variables persists for the duration of a java session in Oracle, you can use them in calls. For example

    create or replace and set the java source named object_store as
    public class bike
    {
    private String number_of_gears;
    public String getGears()
    {
    Return number_of_gears;
    };
    public void setGears (chain sprockets)
    {
    number_of_gears = gears;
    };
    };
    public class bike_shed
    {
    velo1 private static bike;
    public static void setBike (bike, bike)
    {
    velo1 = bike;
    };
    public static bike getBike()
    {
    Return to velo1;
    };
    };
    Public class Tester
    {
    public static void StoreBike (String NumberGears)
    {
    Bicycle bike = new Bike();
    bike.setGears (NumberGears);
    bike_shed.setBike (Bike);
    };
    public static GetBike() Sub
    {
    Bicycle bike = bike_shed.getBike ();
    System.out.println (Bike.getGears ());
    };
    };
    /

    create or replace procedure StoreBike (gears VARCHAR2) Java language
    name ' tester. StoreBike (java.lang.String)';
    /

    create or replace procedure GetBike as java language
    name ' tester. GetBike()';
    /

    exec dbms_java.set_output (100);
    Set serveroutput on;

    exec StoreBike (10);

    exec GetBike();

    Published by: James C on October 18, 2011 12:31

Maybe you are looking for