Appropriate way to pass instance of class to other classes (Java) - java

I have a main class which has a number of instance related methods that are often needed in other classes and I often find myself passing an instance of the main class in the constructor. I often find this goes several layers deep with classes having instances of the main class that has been copied from instance to instance which I can't imagine is good for memory usage.
Is there a way to do this without having to pass the instance in the constructor or a method or at least a way to reduce the memory that is used by the instances of the main class.
To make it clear I am not looking for static methods, it is designed to be able to have more than one instance of the main class.
Example code:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public void someMethod() {
//Do something
}
}
public class Class2 {
private final Main instance;
public Class2(Main instance) {
this.instance = instance;
Class3 class3 = new Class3(instance);
}
}
public class Class3 {
private final Main instance;
public Class3(Main instance) {
this.instance = instance;
instance.someMethod();
}
}

You can use Dependency Injection Design Pattern.
Dependency-Injection-Design-Pattern
Spring, Google Guice and Java EE CDI frameworks facilitate the
process of dependency injection through use of Java Reflection API and
java annotations. All we need is to annotate the field, constructor or
setter method and configure them in configuration xml files or
classes.

You could also use dependency injection to pass on the dependent attributes or objects to required classes.
One such popular framework is Google Guice.

You could make methods like someMethod() in the Main class static, or if that's not possible, make the Main class itself a singleton.
Example of the former approach:
public class Main {
public Main() {
Class2 class2 = new Class2(this);
}
public static void someMethod() {
//Do something
}
}
Now you don't have to pass an instance of Main around any more, because other classes can just call Main.someMethod() directly.

Related

What is proper way to create objects inside method using Guice

What is proper way to create objects inside method of a Singleton object using Guice.
If I have some code like this below, what is a proper way to create instances of Class2?
Class1 is singleton and need to create one new instance of Class2 everytime search is called (so I can not inject it with constructor field...) I will reorganize code if needed.
#Singleton
final class Class1 {
#Inject
private Class1(...){...}
public Class2 search(...){
Class2 newInstance=...
return newInstance;
}
}
I guess I found it.
Need to use providers for such instances.
Obtain class provider in constructor and use provider.get to obtain instances.
Something like:
#Singleton
final class Class1 {
Provider<Class2> p;
#Inject
private Class1(Provider<Class2> pParam;...){
p=pParam;
...
}
public Class2 search(...){
Class2 newInstance=p.get();
return newInstance;
}
}

Passing one instance of an object to different classes without using static or singleton

I am trying to figure out a way to pass one instance of the same class to multiple classes so I am able to build an object. The problem is it cannot be static or use singleton because many users will be hitting the application at the same time and I may run into other issues. Are there any design patterns that would work best with this scenario or if there is some way to use global variables in java? I am trying implement this with an existing rest service that was not designed very well.
public class OneInstanceOf
{//I want to build this map object without static
private Map<String, String> mapIwantToBuild = new HaspMap<String, String>();
public void methodIwantToCall(String name, String value)
{mapIwantToBuild.put(name, value)
}
The common pattern for you task is dependency injection. You can use spring framework for that task.
1.Create configuration with your bean:
#Configuration
public class YourConfiguration {
#Bean
public OneInstanceOf oneInstanceOf {
return new OneInstanceOf();
}
}
2.Inject your bean whatever you want (simplest - use autowiring):
#Component
public class Client1 {
#Autowire
private OneInstanceOf oneInstanceOf;
public void someMethod() {
oneInstanceOf.methodIwantToCall();
}
}
Spring will insure single instance of oneInstanceOf will be injected in all clients.
U can create a setter with parameter of instance class variable, in every class in which you want to pass the instance. Then create a method in one of the classes that calls setter of all those classes and pass parameter instance as parameter to that method.
Like below.
class A{
B b = new B;
set(B b){
C.setB(b);
D.setB(b);
E.setB(b);
}
}

How to make sure that there is just one instance of class in JVM?

I am developing a design pattern, and I want to make sure that here is just one instance of a class in Java Virtual Machine, to funnel all requests for some resource through a single point, but I don't know if it is possible.
I can only think of a way to count instances of a class and destroy all instance after first is created.
Is this a right approach? If not, is there any other way?
Use the singleton pattern. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().
The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance() method (which must be public) then simply returns this instance,
public class Singleton {
private static Singleton instance;
/**
* A private Constructor prevents any other class from
* instantiating.
*/
private Singleton() {
// nothing to do this time
}
/**
* The Static initializer constructs the instance at class
* loading time; this is to simulate a more involved
* construction process (it it were really simple, you'd just
* use an initializer)
*/
static {
instance = new Singleton();
}
/** Static 'instance' method */
public static Singleton getInstance() {
return instance;
}
// other methods protected by singleton-ness would be here...
/** A simple demo method */
public String demoMethod() {
return "demo";
}
}
Note that the method of using “lazy evaluation” in the getInstance() method (which
is advocated in Design Patterns), is not necessary in Java because Java already uses “lazy
loading.” Your singleton class will probably not get loaded unless its getInstance()
is called, so there is no point in trying to defer the singleton construction until it’s needed
by having getInstance() test the singleton variable for null and creating the singleton
there.
Using this class is equally simple: simply get and retain the reference, and invoke methods on it:
public class SingletonDemo {
public static void main(String[] args) {
Singleton tmp = Singleton.getInstance();
tmp.demoMethod();
}
}
Some commentators believe that a singleton should also provide a public final
clone() method that just throws an exception, to avoid subclasses that “cheat” and
clone() the singleton. However, it is clear that a class with only a private constructor
cannot be subclassed, so this paranoia does not appear to be necessary.
That's the well known Singleton pattern: you can implement this as follows:
public class SingletonClass {
//this field contains the single instance every initialized.
private static final instance = new SingletonClass();
//constructor *must* be private, otherwise other classes can make an instance as well
private SingletonClass () {
//initialize
}
//this is the method to obtain the single instance
public static SingletonClass getInstance () {
return instance;
}
}
You then call for the instance (like you would constructing a non-singleton) with:
SingletonClass.getInstance();
But in literature, a Singleton is in general considered to be a bad design idea. Of course this always somewhat depends on the situation, but most programmers advice against it. Only saying it, don't shoot on the messenger...
There is a school of thought that considers the Singleton pattern to in fact be an anti-pattern.
Considering a class A that you only wish to have one of, then an alternative is to have a builder or factory class that itself limits the creation of the number of objects of Class A, and that could be by a simple counter.
The advantage is that Class A no longer needs to worry about that, it concentrates on its real purpose. Every class that uses it no longer has to worry about it being a singleton either (no more getInstance() calls).
You want the Singleton pattern. There is an excellent discussion of how to implement this properly. If you do this right, there will only ever be one instance of the class.
Essentially what you are going to do is create a class, hold a single instantiated object of that class at the static level, and provide a static accessor to get it (getInstance() or similar). Make the constructor final so people can't create their own instances out of the blue. That link above has plenty of great advice on how to do this.
Use enum. In Java enum is the only true way to create a singleton. Private constructors can be still called through reflection.
See this StackOverflow question for more details:
Implementing Singleton with an Enum (in Java)
Discussion:
http://javarevisited.blogspot.com/2012/07/why-enum-singleton-are-better-in-java.html
I can only think of a way to count instances of a class and destroy all instance after first is created. Is this a right approach ? If not, is there any other way ?
The correct technical approach is to declare all of the constructors for the class as private so that instances of the class can only be created by the class itself. Then you code the class only ever create one instance.
Other Answers show some of the ways to implement this, according to the "Singleton" design pattern. However, implementing a singleton like this has some drawbacks, including making it significantly harder to write unit tests.
I prefer lazy singleton class, which overrides readResolve method.
For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.
Lazy singleton using /Initialization-on-demand_holder_idiom:
public final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Key notes:
final keyword prohibits extension of this class by sub-classing
private constructor prohibits direct object creation with new operator in caller classes
readResolve prohibits creation of multiple instances of class during object de-serialization
For that you need to use singleton pattern, I am just posting a demo code for that that may useful for your understanding.
E.g: If I want only one object for this Connect class:
public final class Connect {
private Connect() {}
private volatile static Connect connect = null;
public static Connect getinstance() {
if(connect == null) {
synchronized (Connect.class) {
connect = new Connect();
}
}
return connect;
}
}
Here the constructor is private, so no one can use new keyword to make a new instance.
class A{
private A(){
}
public static A creator(A obj){
A ob=new A();
return ob;
}
void test(){
System.out.println("The method is called");
}
}
class Demo{
public static void main(String[] args){
A ob=null;
ob=A.creator(ob);
ob.test();
}
}

Can Guice assert that a singleton is not directly instantiated?

Is it possible for Guice throw an exception if I try to construct a new instance of a singleton?
For example:
public class MyModule extends AbstractModule {
#Override
protected void configure() {
bind(MySingleton.class).in(Singleton.class);
}
}
#Singleton
public class MySingleton {
MySingleton() { /* ... */ }
}
public class RightWay {
public void withInjector() {
Injector injector = Guice.createInjector(new MyModule());
MySingleton mySingleton = injector.getInstance(MySingleton.class);
}
}
public class AnotherRightWay {
private final MySingleton mySingleton;
#Inject
public AnotherRightWay(MySingleton mySingleton) {
this.mySingleton = mySingleton;
}
}
public class TheWrongWay {
public void directInstantiation() {
MySingleton mySingleton = new MySingleton(); // I want an exception here!
}
}
By making MySingleton's constructor package private, I can limit the scope for mistakes, but of course classes in the same package can still throw a spanner into the works. The advantage here is that my unit tests for AnotherRightWay can easily pass mocks of MySingleton to its constructor.
Or, I could make MySingleton's constructor protected, which Guice can handle, and I can still mock by making my mocks extend MySingleton. But then a MySingleton user could do the same without knowing the danger.
If Guice can throw an exception, I can use reflection in my unit tests to construct mocks, but my users could not easily accidentally create a non-singleton version of MySingleton.
Is this possible? Should I just use either the package-private or protected and learn to love the bomb?
Guice is not magic. You can't force it to do something outside of an Injector, so no, you can't do that, and in fact you shouldn't.
The best way, as you have already noticed, is to make constructor of MySingleton package-private. That way no one outside of the package will be able to construct it but Guice. Since this package is controlled by you, it is safe assumption that no one will create MySingleton in other way than via Guice (using your module, of course).
This is not a "bomb". Package-private modifier is intended exactly for this purpose. It is assumed that you control your packages, so it is fine to make constructors and other things package-private and assume that no one but you will call them.

Guice injector inside a thread

I have a doubt using Guice. I have a class that I call Main that is constructor injected using Guice and a method that every time that is called creates an o thread object of class AppThread. AppThread is a private class inside Main. The problem is that inside the execution of the thread I want to create an object of class ClassX. This object is constructor injected using Guice. I don't know what's the best form to inject the objects of ClassX. My first solution is inject the Injector inside Main and inside the thread use the injector to inject the objects of class ClassX.
Does exists a cleaner approach to inject the dependences inside the thread?
Thanks
Instead of having your own subclass of Thread (which is discouraged anyway) you should write your "thread code" as a regular object that implements Runnable. Your Main class should inject this class (or you can actually inject a Provider<MyRunnable> if you need to instantiate an unknown number of them). Then your Main class can create a new Thread(myRunnable) and it should all fit together nicely.
public class MyMainClass {
#Inject
MyMainClass(Provider<MyRunnable> runnableProvider) { ... }
public void spawnThread() {
new Thread(runnableProvider.get()).start();
}
}
public class MyRunnable implements Runnable {
#Inject
MyRunnable(ClassX myX) { ... }
public void run() {
... do work ...
}
}

Categories