How to have multiple singleton instance when user regenerate the data structure in application? - singleton

I have an application which uses back ground worker(bw) and tasks.
I have one singleton instance in this app..which contains most of the common info about that instance of application. I have different agents listed in my app..and if I switch to different agent, i have to build entire data structure (models/viewmodels/DTOs)
Lets say, for agent "a" one of the bw is spawned...and it uses the above mentioned singleton instance...
Soon I switch to agent "b"...so in my app, i create new data structure for aganet "b". But uses the same singleton instance.
If I change any property in this singleton instance...there is a chance that the new value will be used by bw spawned for agent "a".
Can somebody help me to overcome this situation?
Can I have different singleton instance for different agents ?
Any help would be appreciated. Thanks
EDIT : Any different approach if you can tell me it would be great.

A singleton, by definition, can only exist once. If you want different settings for each user, you will need to use a different architecture. See http://sourcemaking.com/design_patterns/singleton for more information about singletons.

Related

How to share an instance of a singleton class between two windows

I am working with small electron application, and I want to ask one small question.
I need to share a singleton class instance between different two windows of my app.
“Share” means instance which has each class is the same and variables of the instance are the same.
I used affinity parameter in the BrowserWindow() constructor to run two windows in the same renderer process. I suppose if the two windows run in the same process, the two windows share the instance. But actually, the instance and the values of the instance are different.
Is this a correct behavior?
1.If so, could you tell me another way to share an instance between two windows?
2.If not, is this a bug? Or do I need to set another parameter?
affinity option exposes control to chromimum's process model (https://github.com/electron/electron/issues/11484 / https://www.chromium.org/developers/design-documents/process-models) and none of chromium's process model allows share hosted page's context between. Running two site in single process doesn't necessarily mean two hosted sites shares context, especially it exposes whole security concerns around.
There is no such thing for singleton in electron, at least from out of box supported way via electron's supported api surface. Though it's not true sharing, sync via ipc is nearly only way to go.
i use window.open() method to create new BrowserWindow, when use this method, you can paas your javascript singleton class by window
render-process
const modal = window.open(filePath, 'xxx');
modal.window.singletonClass = window.singletonClass;
main process
mainWindow.webContents.on('new-window', ()=> {});

Facade in Object Oriented Programming

In OOP, should a Facade be an object or just a class? Which is better?
Most of the examples in Wikipedia creates Facade as an object which should be instantiated before use.
CarFacade cf = new CarFacade();
cf.start();
Can it be designed to be like this instead?
CarFacade.start();
UPDATE
Can a Facade facilitate a singleton?
A facade
represents a high level API for a complex subsystem (module).
reduces client code dependencies.
This means that your client code only uses the facade and does
not have a lot of dependencies to classes behind that facade.
It is better to use an instance of an interface, because
you can replace it for tests. E.g. mock the subsystem the facade represents.
you can replace it at runtime.
When you use a static methods, your client code is bound to that method implementations at compile-time. This is usually the opposite of the open/close principle.
I said "usually the opposite", because there are examples when static methods are used, but the system is still open for extension. E.g.
ServiceLoader
The static load methods only scan the classpath and lookup service implementations. Thus adding classes and META-INF/services descriptions to the classpath will add other available services without changing the ServiceLoader's code.
Spring's AuthenticationFacade for example uses a ThreadLocal internally. This makes it possible to replace the behavior of the AuthenticationFacade. Thus it is open for extension too.
Finally I think it is better to use an instance and interface like I would use for most of the other classes.
It's two fold. You can use it as a static method. Say for instance in spring security I use AuthenticationFacade to access currently logged in user Principal details like so. AuthenticationFacade.getName()
There are other instances, in which mostly people create an instance of Facade and use it. In my opinion neither approach is superior over the other. Rather it depends on your context.
Finally Facade can use Singleton pattern to make sure that it creates only one instance and provides a global point of access to it.
This question is highly subjective. The only reason I am responding is because I reviewed some of my own code and found where I had written a Façade in one application as a singleton and written almost the same Façade in a different application requiring an instance. I'm going to discuss why I chose each of those routes in their respective applications so that I can evaluate if I made the correct choice.
A façade vs the open/close principle is already explained by #Rene Link. In my personal experience, you have to think of it this way: Does the object hold the state of itself?
Let's say I have a façade that wraps the Azure Storage API for .NET (https://learn.microsoft.com/en-us/azure/storage/common/storage-samples-dotnet)
This facade holds information about how to authenticate against the storage API so that it the client can do something like this:
Azure.Authenticate(username, password);
Azure.CreateFile("My New Text File", "\\FILELOCATION");
As you can see in this example, I have not created an instance and i'm using static methods, therefore following the singleton pattern. While this makes for code that is more concise, I now have an issue if I need to authenticate to a given path with a different credential than the one already provided, I would have to do something like this:
Azure.Authenticate(username, password)
Azure.CreateFile("My New Text File", "\\FILELOCATION");
Azure.Authenticate(username2, password2);
Azure.CreateFile("My Restrictied Text File", "\\RESTRTICTEDFILELOCATION");
While this would work, it can be hard to determine why authentication failed when I call Azure.ReadFile, as I have no idea what username and password may have been passed into the singleton from thread4 on form2 (which is no where to found) This is a prime example of where you should be using an instance. It would make much more since to do something like this:
Using (AzureFacade myAzure = Azure.Authenticate(username, password))
{
Azure.CreateFile("My New Text File", "\\FILELOCATION"); // I will always know the username and password.
}
With that said, what happens if the developer needs to create a file in Azure in a method that has no idea what the username and password to Azure may be. A good example of this would be an application that periodically connects to Azure and performs some multi-threaded tasks. In said application, the user setups a connection string to azure and all mulit-threaded tasks are performed using that connection string. Therefore, there is no need to create an instance for each thread (as the state of the object will always be the same) However, in order to maintain thread safety, you don't want to share the same instance across all the threads. This is where a singleton, thread-safe pattern may come into play. (Spring's AuthenticationFacade according to #Rene Link) So that I could do something like this (psudocode)
Thread[] allTask = // Create 5 threads
Azure.Authenticate(username, password) // Authenticate for all 5 threads.
allTask.start(myfunction)
void myFunction()
{
Azure.CreateFile("x");
}
Therefore, the choice between an instance of a façade v. a singleton façade is completely dependent on the intended application of the facade, however both can definitely exist.

How can I cleanly write abstractions for interacting with RESTful resources?

I have a simple REST client that works well. In my application code I do something like this:
restClient = new RestClient(configurationData)
restClient.get('/person/1') //Get Person
restClient.get('/equipment/auto/3') //Get an Auto
restClient.get('/house/7') //Get a House
That works well but things are getting more complicated and I would like to divorce the application code from the specific resource locations.
I'd like to be able to write a wrapper around the service, which will store the resource locations and not require me to put them in my application code. I would expect my code to start looking more like this:
restClient = new RestClient(configurationData)
restClient.getPerson(1) //Get Person
restClient.getAuto(3) //Get an Auto
restClient.getHouse(7) //Get a House
I started adding these wrappers inside of my RestClient class but it got very bloated very fast, and it felt that the abstraction should be at a higher level. Mixing Resource-specifics with my client also felt wrong.
So, instead I subclassed RestClient, and each resource has its own class. The problem is that now I have to instantiate a new client for every different resource type:
personRestClient = new PersonRestClient(configurationData)
personRestClient.get(1);
autoRestClient = new AutoRestClient(configurationData)
autoRestClient.get(3);
housesRestClient = new HousesRestClient(configurationData)
housesRestClient.get(7);
But now I've created a new Client class for each Resource and I am fairly certain that is a very bad thing to do. It's also a pain because I have to tie my connection configuration data to each one, when this should only happen once.
Is there a good example or pattern I should be following when I want to write abstractions for my Resources? My base RestClient works fine but I dislike having to put the server-side API locations in my application code. But I also don't want to have to instantiate one specialized client class for each Resource I want to interact with.
I am in a similar situation, and have what I consider to be a good implementation with the appropriate abstractions. Whether my solution is the best practice or not, I cannot guarantee it, but it is fairly lightweight. Here is how I have it architected:
My UI layer needs to make calls into my REST service, so I created an abstraction called ServiceManagers.Interfaces.IAccountManager. The interface has methods called GetAccounts(Int64 userId).
Then I created a Rest.AccountManager that implemented this Interface, and injected that into my AccountController. The Rest.AccountManager is what wraps the REST specifics (URL, get/post/put..., parameters, etc).
So, now my UI code only has to call accountManager.GetAccounts(userId). You can create an all-encompassing interface so that you only have a Get, but I feel that is less expressive. It is ok to have many different interfaces for each component(ie: PersonManager, HouseManager, AutoManager), because each are a separate concern returning different data. Do not be afraid of having a lot of interfaces and classes, as long as your names are expressive.
In my example, my UI has a different manager for each controller, and the calls made fit each controller appropriately (ie. GetAccounts for AccountController, GetPeople for PeopleController).
Also, as to the root configuration data, you can just use a configurationCreationFactory class or something. That way all implementations have the appropriate configuration with the core logic in one location.
This can be a hard thing to explain, and I know I did not do a perfect job, but hopefully this helps a little. I will try to go back through and clean it up later, especially if you do not get my point :)
I am thinking something like this, again some way of mapping your end points to the client. You can have the mapping as an xml or a properties file which can be loaded and cached during the app start. The file should have key value pairs
PERSON_ENDPOINT=/person/
AUTO_ENDPOINT=/equipment/auto/...
The client should pass this key to the factory may be ClientFactory which has this xml cache and retrieves the end point from the cached file. The parameters can be passed to the factory as custom object or a map. The factory gives back the complete end point say "/person/1" which you can pass to your client. This way you dont need to have different classes for the client. If you dont like the xml or a file you can have it as a static map with key value pairs. If its an xml or file you dont need a code change every time that is the advantage.
Hope this helps you.

saving PendingIntents

i have an android application that handles a sql-lite database and i need to to beable save a unique PendingIntent, and a unique long for every rowId in the database. The PendingIntent and long have to be reachable from all the applications classes so i can easily 1)retrieve them 2)cancel it(the PendingIntent) and 3)change them from anywhere is the applications code.
i am sure someone can help! thankyou :)
PS. if it makes any difference i have 2 sql databases that both need this.
I would suggest:
You have a service that gets loaded on startup with BOOT_COMPLETED event.
The service polls the db and creates a map of special objects, which contain PendingIntent, your unique long and whatever more.
From the activity you bind to a service and ask it to do somethings, would it be returning an intent, or creating new or whatever.
Application class can know about the service from the activity, you have binded to the service.
I'm not sure the service is necessary here. If your work with pending intents begins from the concreate activity, you can simplify this solution with using Singleton pattern for the class, which contains the pending intents data.

How to pass user details between objects in VB.net?

I'm redesigning an old VB6 application into VB.net and there is one thing I'm not sure on the best way to do.
In the VB6 application whenever we created a new instance of a component, we would pass in the user details (user name and the like) so we new who was performing the tasks. However, no that I'm redesigning I've created some nice class designs, but I'm having to add in user details into every class and it just looks wrong.
Is there a VB.net way of doing this so my classes can just have class specific details? Some way so that if my classes need to know who is performing a task, they can get the information themselves, rather than having it passed in whenever the objects are created?
You could put the details of the current user in a class that is accessible by all class instances of your application.
One place you could consider putting it is in the MyApplication class. You could also create a module and place it there.
Could you wrap the current user details into an object, and pass the object when you create the others? They would just keep a reference, and delegate to the user object for user-specific stuff.
That seems like the obvious way?