I was just curious where exactly the singleton pattern is used...
I know how the pattern works and where it can be used but i personally never used in any real application.
Can some one give an example where it can be used..
I would really appreciate if some one can explain how and where they have used in real application.
Thanks,
Swati
Typically singletons are used for global configuration. The simplest example would be LogManager - there's a static LogManager.getLogManager() method, and a single global instance is used.
In fact this isn't a "true" singleton as you can derive your own class from LogManager and create extra instances that way - but it's typically used as a singleton.
Another example would be java.lang.Runtime - from the docs:
Every Java application has a single
instance of class Runtime that allows
the application to interface with the
environment in which the application
is running. The current runtime can be
obtained from the getRuntime method.
That's pretty much the definition of a singleton :)
Now the singleton pattern is mostly frowned upon these days - it introduces tight coupling, and makes things which use the singleton harder to test, as you can't easily mock out that component. If you can get away without it, so much the better. Inject your dependencies where possible instead.
Some examples:
Hardware access
Database connections
Config files
I used the singleton pattern in an online Football Team Store System. we applied the singleton pattern to a ShoppingCart class.
You only needed one instance of the cart per an application instance. so the singleton seemed like it's the best fit for that situation.
Consider the situation of AudioDriverService which is designed in Singleton Pattern. So we are allowed to create just a single instance of AudioDriverService class. Now actually your Windows Media Player or Youtube Player both will share the same object of AudioDriverService rather than creating a new instance.
When you use Logger, you use Singleton pattern for the Logger class. In case it is not Singleton, every client will have its own Logger object and there will be concurrent access on the Logger instance in Multithreaded environment, and multiple clients will create/write to the Log file concurrently, this leads to data corruption.
For example running a trial version of a software with one license and one database connection ,that uses singleton pattern in real word. may be the guru jon skeet can provide example like this.
Singleton pattern is generally useful when the object that is created once and shared
across different threads/Applications.
Consider the case that you are implementing the properties load class for a printer.
Now Printers can be of variant properties. For eg:-
Mono Printer,
Color Printer,
Automatic Scanner Support Printer and so on...
Every time on boot this config file has to load to enable a few buttons/ applications
on the UI say tab or any Printer UI.
The value of the supported features are stored in form of a config table like say 1 if
feature supported and 0 if not supported.
Based on the supported features we enable disable certain functionalities and application
on the UI. Now this config file location in case of printers manufactured by a single company
are always stored at a fixed path.
The file values would change/would be read only in the following scenarios:-
1. On Boot.
2. on Addition or deletion of any new hardware peripheral.
We can use a singleton class to implement the reading of configuration files. As the same values
i.e. the config does not change on UI intervention and can be changed only on hardware intervention.
This is one example I can think of where we can implement Singleton design pattern.
Singleton is a nice design pattern. Before deciding on the pattern first do an in depth analysis of your problem and the solution. If in your solution some object has only one instance and you want to model that in your design then you should use singleton pattern. For example if you are modelling a PC in the software there can be only one instance of a PC with respect to your running program. As Jon Skeet said java.lang.Runtime is modelled as a singleton because for all the java objects that are loaded and running inside a java runtime there is only one instance of runtime.
Again lot of times it is used for the wrong reasons. Never create a singleton so that you can easily access the object (like Object::instance() ) from anywhere without passing the object around. The is the worst use I have ever come across.
I use a media player in my android app, so I extend the mediaplayer class, and used the singleton pattern because I need only one instance, and be able to call the same instance in any other part of my app for check if is playing, or what file is current playing.
Hope it helps you, regards!!!!
Singleton Pattern can be used for loading the configuration , say in a web application, we are supposed to generate a file which is to be stored somewhere in the server. Now, that location can fetched from a config file(properties file) using a singleton class.since the location is to be unique and might change frequently in future, so we use a config file so as can be modified without deploying the application so as to reflect the changes and location will be global and unique through out the application
I used a singleton (actually a couple of them) in an application that used pureMVC. We were unhappy about the complexity this framework introduced (it became complicated and tiering to track method calls through the mvc layers). So we used a central singleton as a mediator to better separate the layers from each other.
Singleton Class is basically used when you have to allow only single instantiation of the class.
Taking real world example, In case of OOP designing of a library, we can create library class as singleton class.
Related
I've read several post regarding singleton class destruction or singleton pattern is bad in android like this and this
But I am not able to understand how to declare a singleton class properly or use sharedpreference for persistance can anyone provide any example on how to maintain global objects across application or how to achieve this in proper way any help is appreciated.
I think this link you mentioned is quite good.As my personal experience the best way to maintain global objects in an application is to use a class that extends from Application class, then you can manage objects by setter and getter methods in that class.This technically works like a Singleton in android except most of house keeping is done by android so it's very wise to use this mechanism instead of singleton.
On the other hand shared preferences has entirely different job and used for mainly storing some user data and behavior
To save data between process termination you have to use serialization in any form.
The easiest way is to use sharedpreferences + gson.
Singleton would not help because all data with the process will be wiped, OS have a handler to save state in "low memory" situations but it still uses serialization (bundles).
You may use singleton with sharedpreferences, data clients (activities) have to notify about destruction, so singleton can dump data. At start singleton will load data again.
But be aware of possible inconstancy - what if an app will crash?
Things get trickier with multiple processes in one application.
In android, are using static variables a recommended practice?
E.g, implementing a Singleton pattern in Java, I usually do:
private static A the_instance;
public static A getInstance() {
if (the_instance == null) {
the_instance = new A();
}
return the_instance;
}
Also, when does this get cleaned up by the Android JVM?
static fields are attached to the Class instance as a whole, which is in turn attached to the ClassLoader which loaded the class. the_instance would be unloaded when the entire ClassLoader is reclaimed. I am 90% sure this happens when Android destroys the app (not when it goes into the background, or pauses, but is completely shut down.)
So, think of it as living as long as your app runs. Is Singleton a good idea? People have different views. I think it's fine when used appropriately, myself. I don't think the answer changes much on Android. Memory usage isn't the issue per se; if you need to load a bunch of stuff in memory, that's either a problem or it isn't, regardless of whether you encapsulate the data in a Singleton.
I think static variables are OK.
This is what Android doc says:
http://developer.android.com/guide/appendix/faq/framework.html
How do I pass data between Activities/Services within a single application?
A public static field/method
An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.
Contrary to what other people say - it is more than ok. Granted, it has some structure to it. In the official googlesamples/android-architecture repo it is used under todo-mvp-clean (Todo app implementing MVP pattern and following Clean Architecture principles).
Check out this file.
What you can see is a lot of static methods referencing singleton getters.
Modern, less error prone and convenient alternative is the Dagger DI framework.
I'm not sure if such approach is good for mobile platform where you have limited memory available to you. Not to mention that the application will be run on a multi-tasking enabled device.
I think, this approach may hog memory from the device but I have no document to support this. Perhaps someone who's more educated than me can share their thoughts.
No. Don't do it! Singleton is an anti-patern!. Instead, use dependency injection, whether via a framework (such as via Dagger or Roboguice) or by explicitly passing the instantiated object.
I am developing an application where I need to create an object and multiple classes have to access and modify that object. How to see the recent changes made by the other class object and how to access the object centrally through all the classes with out passing that object as a parameter across all the classes?
I am creating an Apache POI document where I am adding multiple tables, multiple headers/footers and paragraphs. I want only a single XWPFDocument object present in my application.
Is there any design pattern we can achieve this?
Well the singleton design pattern would work - but isn't terribly clean; you end up with global static state which is hard to keep track of and hard to test. It's often considered an anti-pattern these days. There are a very few cases where it still makes sense, but I try to avoid it.
A better approach would be to use dependency injection: make each class which needs one of these objects declare a constructor parameter of that type (or possibly have a settable property). Each class shouldn't care too much about how shared or otherwise the object is (beyond being aware that it can be shared). Then it's up to the code which initializes the application to decide which objects should be shared.
There are various dependency injection frameworks available for Java, including Guice and Spring. The idea of these frameworks is to automatically wire up all the dependencies in your application, given appropriate configuration.
There is Singleton Pattern for this, it creates a single instance for the application and is shared without passing around.
But it not not the best of options.
Why is it a bad option?
It is not good for testability of code
Not extensible in design
Better than Singleton Pattern is an application wide single instance
Create a single object for the application and share it using some context object. More on this is explained by Misko in his guide to testable code
single instance and not Singleton Pattern
It stands for an application wide single instance, which DOES NOT inforce its singletonness through a static instance field.
Why are Singletons hard to test?
Static access prevents collaborating with a subclass or wrapped version of another class. By hard-coding the dependency, we lose the power and flexibility of polymorphism.
-Every test using global state needs it to start in an expected state, or the test will fail. But another object might have mutated that global state in a previous test.
Global state often prevents tests from being able to run in parallel, which forces test suites to run slower.
If you add a new test (which doesn’t clean up global state) and it runs in the middle of the suite, another test may fail that runs after it.
Singletons enforcing their own “Singletonness” end up cheating.
You’ll often see mutator methods such as reset() or setForTest(…) on so-called singletons, because you’ll need to change the instance during tests. If you forget to reset the Singleton after a test, a later use will use the stale underlying instance and may fail in a way that’s difficult to debug.
The question is old hat - what is a proper design to support a configuration file or system configurations across our system? I've identified the following requirements:
Should be able to reload live and have changes picked up instantly with no redeploying
For software applications that rely on the same, e.g., SQL or memcached credentials, should be possible to introduce the change in an isolated place and deploy in one swoop, even if applications are on separate machines in separate locations
Many processes/machines running the same application supported
And the parts of this design I am struggling with:
Should each major class take its own "Config" class as an input parameter to the constructor? Should there be a factory responsible for instantiating with respect to the right config? Or should each class just read from its own config and reload somewhat automatically?
If class B derives from class A, or composes around it, would it make sense for the Config file to be inherited?
Say class A is constructed by M1 and M2 (M for "main") and M1 is responsible for instantiating a resource. Say the resource relies on MySQL credentials that I expect to be common between M1 and M2, is there a way to avoid the tradeoff of break ownership and put in A's config v. duplicate the resource across M1 and M2's config?
These are the design issues I'm dealing with right now and don't really know the design patterns or frameworks that work here. I'm in Java so any libraries that solve this are very welcome.
You may want to check out Apache Commons Config, which provides a wide range of features. You can specify multiple configuration sources, and arrange these into a hierarchy. One feature of particular interest is the provision for Configuration Events, allowing your components to register their interest in configuration changes.
The goal of changing config on the fly is seductive, but requires some thought around the design. You need to manage those changes carefully (e.g. what happens if you shrink queue sizes - do you throw away existing elements on the queue ?)
Should each major class take its own "Config" class as an input parameter to the constructor?
No, that sounds like an awful design which would unnecessarily overcomplicate a lot of code. I would recommend you to implement a global Configuration class as a singleton. Singleton means that there is only one configuration object, which is a private static variable of your Configuration class and can be acquired with a public static getInstance() method whenever it is needed.
This configuration object should store all configuration parameters as key/value pairs.
In android, are using static variables a recommended practice?
E.g, implementing a Singleton pattern in Java, I usually do:
private static A the_instance;
public static A getInstance() {
if (the_instance == null) {
the_instance = new A();
}
return the_instance;
}
Also, when does this get cleaned up by the Android JVM?
static fields are attached to the Class instance as a whole, which is in turn attached to the ClassLoader which loaded the class. the_instance would be unloaded when the entire ClassLoader is reclaimed. I am 90% sure this happens when Android destroys the app (not when it goes into the background, or pauses, but is completely shut down.)
So, think of it as living as long as your app runs. Is Singleton a good idea? People have different views. I think it's fine when used appropriately, myself. I don't think the answer changes much on Android. Memory usage isn't the issue per se; if you need to load a bunch of stuff in memory, that's either a problem or it isn't, regardless of whether you encapsulate the data in a Singleton.
I think static variables are OK.
This is what Android doc says:
http://developer.android.com/guide/appendix/faq/framework.html
How do I pass data between Activities/Services within a single application?
A public static field/method
An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.
Contrary to what other people say - it is more than ok. Granted, it has some structure to it. In the official googlesamples/android-architecture repo it is used under todo-mvp-clean (Todo app implementing MVP pattern and following Clean Architecture principles).
Check out this file.
What you can see is a lot of static methods referencing singleton getters.
Modern, less error prone and convenient alternative is the Dagger DI framework.
I'm not sure if such approach is good for mobile platform where you have limited memory available to you. Not to mention that the application will be run on a multi-tasking enabled device.
I think, this approach may hog memory from the device but I have no document to support this. Perhaps someone who's more educated than me can share their thoughts.
No. Don't do it! Singleton is an anti-patern!. Instead, use dependency injection, whether via a framework (such as via Dagger or Roboguice) or by explicitly passing the instantiated object.