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.
Related
Is it common practice to communicate via field references. Let's say I have an instance injected all over my program. Since all classes are referencing the same instance I can simply change it's state, instead of informing all dependent classes via method calls? Isn't that a big advantage of dependency injection? Or do I turn a dependency injected variable turn into a global variable?
Variables don't get injected. Values get injected. When you inject a bean into another bean you are injecting that reference. References are values, see
Is Java "pass-by-reference" or "pass-by-value"?.
You can have some spring bean in singleton scope that different parts of the application call, with some method which returns a value. For instance a spring boot application can have a Clock configured that various services or other components have injected into them, where they call the clock to get the current time.
If you do have a bean that contains some mutable value that gets set, be aware its scope will be limited to the application instance. If you have multiple instances of the application deployed. each one will have its own separate bean. Also changes aren't going to be guaranteed to be visible across threads unless you enforce that (with tools like locking, the volatile keyword, atomic variables, etc.).
Fundamentally OO is about message-passing, not about sharing memory. We want to limit global state because it's hard to reason about. Especially when you consider the high-concurrency of a web application and how quickly things can be changing, and how difficult it is to ensure changes are visible, in a lot of cases it's better to find alternatives to global variables.
Assuming that the injected type is configured to use a Singleton, there shouldn't be any behavioral difference between using dependency injection and accessing a Singleton directly.
The advantages to using Dependency Injection generally center around how the code is written, and how it allows you to decouple the consuming classes from the specific requirement for that injected object to actually be a singleton.
For example, if you want to unit-test your consuming class, you probably want complete control over what the class perceives as the current state, and you probably don't want any effects of the code your testing to carry over into other unit tests: you don't want a test to pass when it is run all by itself but fail if it happens to run immediately after some other test.
Using Dependency Injection, your unit tests can encapsulate the entire interaction with the code being tested. The code that instantiates the class has complete control over what gets injected, so it doesn't have to provide a singleton value.
By separating the class that consumes an injected value from any specific knowledge about where that value comes from, or what its life cycle looks like, you're better able to maintain separation of concerns. If a future change requires a value to no longer be a singleton (e.g. maybe it needs to be dependent on the current user), you're in a better position to change how that injected value is provided without having to change code all over your code base.
I am working on a j2ee webapp divided in several modules. I have some metadata such as user name and preferences that I would like to access from everywhere in the app, and maybe also gather data similar to logging information but specific to a request and store it in those metadata so that I could optionally send it back as debug information to the user.
Aside from passing a generic context object throughout every method from the upper presentation classes to the downer daos or using AOP, the only solution that came in mind was using a threadlocal "Context" object very similar to a session BTW, and add a filter for binding it on ongoing request and unbinding it on response.
But such thing feels a little hacky since this breaks several patterns and could possibly make things complicated when it comes to testing and debugging so I wanted to ask if from your experience it is ok to proceed like this?
ThreadLocal is a hack to make up for bad design and/or architecture. It's a terrible practice:
It's a pool of one or more global variables and global variables in any language are bad practice (there's a whole set of problems associated with global variables - search it on the net)
It may lead to memory leaks, in any J2EE container than manages its threads, if you don't handle it well.
What's even worse practice is to use the ThreadLocal in the various layers.
Data communicated from one layer to another should be passed using Transfer Objects (a standard pattern).
It's hard to think of a good justification for using ThreadLocal. Perhaps if you need to communicate some values between 2 layers that have a third/middle layer between them, and you don't have the means to make changes to that middle layer. But if that's the case, I would look for a better middle layer.
In any case, if you store the values in one specific point in the code and retrieve it in another single point, then it may be excusable, otherwise you just never know what side affects any executing method may have on the values in the ThreadLocal.
Personally I prefer passing a context object, as the fact that the same thread is used for processing is an artifact of the implementation, and you shouldn't rely on such artifacts. The moment you want to use other threads, you'll hit a wall.
If those states are encapsulated in a Context object, I think that's clean enough.
When it comes to testing, the best tool is dependency injection. It allows to inject fake dependencies into the object under test.
And all dependency injection frameworks (Spring, CDI, Guice) have the concept of a scope (where request is one of these scopes). Under the hood, beans stored in the request scoped are indeed associated with a ThreadLocal variable, but this is all done by the dependency injection framework.
What I would do is thus to use a DI framework, which would make request-scope objects available anywhere, but without having to look them up, which would break testability. Just inject a request-scoped object where you want to use it, and the DI framework will retrieve it for you.
You must know that a servlet container can / will re-use threads for requests so if you do use ThreadLocals, you'll need to clean up after yourself once the request is finished (perhaps using a filter)
If you are the only developer in the project and you think you gain something: just do it! Because it is your time. But, be prepared to revert the decision and reorganize the code base later, as should be always the case.
Let's say there are ten developers on the project. Everybody might like to have its thread local variable to pass on parameters like currency, locale, roles, maybe it becomes even a HashMap....
I think in the end, not everything which is feasible, should be done. Complexity will strike back on you....
ThreadLocal can lead to memory leak if we do not set null manually once its out of scope.
I am developing some software with a few people and from the completed class diagrams there is one Database class and for example the Order class has two constructors, one which has no arguments and one which excepts an id. It also has a save() method so going by those class features I am assuming if you supply an id in the constructor the class will use the Database class and populate the objects properties and also there is no place to inject this Database class in the constructor or in a setter method so I presume they want to use a Singleton.
I want to know if my arguments are valid before I say it to them so here they are:
Doing it this way breaks the SOLID Single Responsibility Principle(SRP)
It introduces tight coupling between all our classes which need the Database class
It hides our objects dependencies
It makes unit testing much harder
Introduces unnecessary global state
Would they be valid arguments and are there any more flaws doing it this way? If my points are valid would it be worth saying it to them?
Thanks.
This is a well-known pattern called active record. It is commonly employed in several large frameworks such as Ruby on Rails. It does have the downsides that you mention, and I think that you should highlight the potential problem, but not without having any alternatives to discuss.
One common alternative is to have a service façade which saves you objects - a set of DAOs. With this pattern you make accessing the database more explicit and less convenient, but IMO you decrease DB coupling in your main app. This is better in a SRP perspective, as you mention, which amongst others makes testing much easier.
When is a singleton class preferred over a class that has only static methods and a private default constructor?
Please vote.
Use a singleton to better control when initialization occurs. With a static class, any initialization must be at class load-time, which you have little control over. For example, a simple reference to a static final MEMBER will trigger class loading. With a singleton, initialization can trivially be deferred till much later - typically, till first time of use.
Reasons to delay initialization may be:
it's expensive and you don't always need it for that class
you can't initialize till some other resource is initialized (say, a database connection). In this case, a lazily-instantiated singleton often provides correct order of operations without any explicit control - if it's not referenced till after the other resource is initialized, everything happens for free.
Use a singleton to improve testability. If you need to make some kind of mock object (in the broad sense) of the singleton in order to test its clients, one way to do it is to put an interface on its use, and supply a test singleton that's of a different class but implements the same interface.
Using a singleton makes initialization testing easier as well.
Use a singleton when you might need to debug initialization. Stack traces from static initialization can be puzzling. Debugging can be puzzling too. If the class is loaded early, it may break before a breakpoint on the first line in main() is even hit.
When is a singleton class preferred over a class that has only static methods and a private default constructor?
When you need an instance. For example, to pass as method argument.
The main reason for only having static methods is when you just need a toolbox to pack some functions together.
I use singletons for mainly two reasons:
It is really expensive (time or memory) to construct the object, and
I want to only ever do it once.
The data associated with the class
needs to be the same in every instance of the class.
If you have some state you need to store, a singleton is the way to go. For instance, if your class needs to load some configuration from a properties file.
Static method is not dynamic, this is a big different with singleton class instance. So if you need to extends from a class and override some method, the second way won't work.
And the for the second way, you may need to use some static references which may lead to memory leak.
I would say that a singleton class would be preferred only in one case: when you have some configuration to store that is system wide, will rarely (if ever) need to be refreshed.
As an example of what I mean, I have a singleton pattern in one of my applications that represents the NAT device of the user's internet connection. This application is intended for desktop use, and so would rarely (if ever) see a change in the internet connection. Presumably the user could carry their laptop to a new location, and this would change; however, there is a method to recreate the state in this event, but this is very infrequently changed state that can take several seconds to initialize.
This need to keep expensive, infrequently changing, and globally applicable state is best done by either an application scoped bean (my preferred option) or a singleton pattern bean. Static methods aren't as good for preserving this kind of state, though you could also accomplish this using static fields as well to make a pseudo-singleton. (Not sure if there's a better name for this - probably)
In general, my recommendation is not to use singleton like patterns if you can avoid it, as it makes re-use more difficult. If you're using a CDI framework, scope your bean at the application level for easier re-use. (This may not be a concern of yours - if not, you may safely ignore this advice)
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.