How can I create singleton instance of an dependency class? - java

I am bit new to patterns and using them.
I want to configure an object of a dependency class(say A.) once and use it through out my app. I tried making a singleton wrapper class on top of it, but failed miserably. I tried something like:
public class B {
public static A a = new A();
public static A getInstance() {
return a;
}
private B() {
a.configure();
}
}
I think calling B.getInstance() won't configure the object here. What I want here is to configure A's instance once and use it everywhere.

Basically your singleton class is B right ? in your sample code you use the singleton pattern for the inner A, which doesnt make much sense.
From my understanding you should go for something like that :
public class B {
private static B _instance;
public static B getInstance() {
if (_instance == null) {
_instance = new B(new A());
}
return _instance;
}
private A _a;
private B (A a) {
_a = a;
_a.configure();
}
}

Related

Singleton class return two different singleton objects

I want to design a class which should return a singleton of some third party object.
For e.g., I want to create a singleton of 3rd party B class object. Below is the design I have made.
public class A{
private static A A = null;
private static B B = null;
private A() {
B = code to instantiate B Object;
}
public static synchronized A getAInstance() {
if(A ==null){
synchronized(A.class){
if(A == null){
A = new A();
}
}
}
return A;
}
public B getB(){
return B;
}
}
Can you please help me is this a proper singleton
If I understand your question correctly, you want to have a single instance of a third party class. First of all it is a good practice to access third party obj via wrapper class obj,(clean code handbook of agile software craftsmanship chapter8), in your case class b is wrapped by class a.
In order to make a single instance of class b you can just make it an instance variable of class a and then make the class a singleton, code bellow
Public class A{
private static A A = null;
private B B = null;
private A() {
B = code to instantiate B Object;
}
public static synchronized A getAInstance() {
if(A ==null){
synchronized(A.class){
if(A == null){
A = new A();
}
}
}
return A;
}
public B getB(){
return B;
}
}
You can simply have this structure. No explicit synchrnoization required, just leave it to JVM.
public class A {
private static class BInstanceHolder {
B BInstance = new B();
}
private A(){}
public static B getB(){
return BInstanceHolder.BInstance;
}
}
If you only want to have one copy of B, just do it that way!
You dont even need a Singleton of Class A.
So you could try:
public final class A{
private A(){}
private static B instance;
static{
instance = code to instantiate B Object
}
public static synchronized B getInstance() {
return B;
}
}
The static Block will create a instance of B when the Class is first mentioned and will instantiate the instance. The constructor will prevent the A from being made, but you can still access the only instance of B.

Get an already existing object from another class

Im very new to programming and want to know if I can somehow get the object from a class where I already used new MyClass(); to use it in another class and that I don't need to use new MyClass(); again. Hope you get the point.
Some very simple example:
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass
{
// This is where I want to use the object from class Something()
// like
getObjectFromClass()
}
You can use Singleton pattern to achieve this
This is kickoff example of such object. It has a private constructor and public class method getInstance:
static methods, which have the static modifier in their declarations,
should be invoked with the class name, without the need for creating
an instance of the class
When we make a call to getInstance it checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.
public class SingletonObject {
private static int instantiationCounter = 0; //we use this class variable to count how many times this object was instantiated
private static volatile SingletonObject instance;
private SingletonObject() {
instantiationCounter++;
}
public static SingletonObject getInstance() {
if (instance == null ) {
instance = new SingletonObject();
}
return instance;
}
public int getInstantiationCounter(){
return instantiationCounter;
}
}
To check how does this work you can use the following code:
public static void main(String[] args) {
SingletonObject object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
}
Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter() method.
Consider this simple example
class Something {
private int a=10;
public int getA() {
return a;
}
}
Here is the First which has a public method which return the object that i created in this class for the Something Class
class MyFirstClass {
private Something st;
public MyFirstClass() {
this.st = new Something();
}
public Something getSt() {
return st;
}
}
Accessing it from another Class
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt().getA());
}
}
Output: 10
If You wan't to verify
Inject this function in MyFirstClass
public void printHashcode(){
System.out.println(st);
}
and then print the hash codes from both methods in MySecondClass
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt());
my.printHashcode();
}
}
You will see that indeed you are using the Object created in MyFirstClass in MySecondClass.
Because this will give you same hashcode output.
Output On my machine.
Something#2677622b
Something#2677622b
Instead of using the Singleton pattern, a better pattern to use is dependency injection. Essentially, you instantiate the class you want to share, and pass it in the constructor of every class that needs it.
public class MainClass {
public static void main(String[] args) {
SharedClass sharedClass = new SharedClass();
ClassA classA = new ClassA(sharedClass);
ClassB classB = new ClassB(sharedClass);
}
}
public class ClassA {
private SharedClass sharedClass;
public ClassA(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
public class ClassB {
private SharedClass sharedClass;
public ClassB(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolve is implemented.
Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.
Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.
You should rework your Something class like this to achieve singleton:
public class Something {
private static final Something INSTANCE = new Something ();
private Something () {
// exists to defeat instantiation
}
public Something getInstance() {
return INSTANCE;
}
public void service() {
//...
}
public void anotherService() {
//..
}
}
If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.
public class SuperClass{
Something st = new Something();
public Something getObjectFromClass(){
return st;
}
}
public class MyFirstClass extends SuperClass{
getObjectFromClass();
}
public class MySecondClass extends SuperClass{
getObjectFromClass();
}
Otherwise, if you plan to use that instance somewhere else you should use a
Singleton object. The easiest way of doing this is:
enum Singleton
{
INSTANCE;
private final Something obj;
Singleton()
{
obj = new Something();
}
public Something getObject()
{
return obj;
}
}
You use it:
Singleton.INSTANCE.getObject();
Okay firstly you can use inheritance e.g.
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method(); //Method from myfirstclass accessible from second class object
}
Or if you dont want any objects and just the method you can implement interfaces e.g.
public interface MyFirstClass
{
//example method
public abstract void saying(); //no body required
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass implements MyFirstClass //Have to implement methods
{
public void saying(){ //Method implemented from firstClass no obj
System.out.println("Hello World");
}
getObjectFromClass()
}

creating an object that shares its property among classes

I would like to make an object of a class A and it is initialized in class B, class C, and class D
This object should be shared; that is if any changes made to objA in these classes(C and D), its content remains the same even after objC,'objD' are destroyed, supposely that class B is the main class. I would like to use its property is class B
class A {}
class B
{
initialize class A object and use-change its property
initialize class C object and use-change its property
initialize class D object and use-change its property
}
class C{initialize class A object and use-change its property}
class D{initialize class A object and use-change its property}
class X{initialize B and destroy objC,objD, from objB use property of objA of class B}
A non static attempt would look like this:
Your target object:
public class A {
}
Your classes, that do something with the object:
public class C {
private final A a;
public C(final A a) {
this.a = a;
}
public foo() {
// do something with a
}
}
public class D {
private final A a;
public D(final A a) {
this.a = a;
}
public otherFoo() {
// do something with a
}
}
Your main class:
public class B {
public static void main(String[] args) {
final A a = new A();
final C c = new C(a);
final D d = new D(a);
c.foo();
d.otherFoo();
}
}
Try making the object static that way any changes made to one instance of that object will be consistent across all objects that use that object that are in the same thread.
This is essentially a singleton pattern, you can pass your class around or get it from the main. I prefer the latter personally, like so:
public class YourMain {
private final ClassA clazzA;
private final ClassB clazzB;
private final ClassC clazzC;
private final ClassD clazzD;
public YourMain() {
this.clazzA = new ClassA();
this.clazzB = new ClassB(this);
this.clazzC = new ClassC(this);
this.clazzD = new ClassD(this);
this.clazzB.doSomething();
}
public ClassA getClassA() {
return this.clazzA;
}
}
From there, you can chain back up to your main class in the other classes:
public class ClassB {
private final YourMain project;
public ClassB(YourMain project) {
this.project = project;
}
public void doSomething() {
this.project.getClassA().someMethod();
}
}
Of course, this isn't 100% what you would implement it like (you need to mind the order you load things in if you are passing your main class instance), but for something like this I usually find it is the cleanest and provides the easiest availability to all my classes across a project.

Get instance of subclass with superclass static method

I have a superclass that I would like to forward a static method called getInstance() to all subclasses.
When creating an instance of a subclass, I then register the instance in the superclass (perhaps using a hashtable, where the key is based on getClass()). Then, I wish to use the aforementioned static method ( getInstance ) where the superclass method will return the instance of the correct type.
For example, I have a superclass A, and a subclass B extends A.
I want to write a static method A.getInstance(); when called from B (B.getInstance()), I would like it to return the instance of B that I stored earlier.
Its kinda hard to explain, but I am going to be using this superclass a lot, and I would rather not code a getInstance method into every single subclass.
How would I go about doing something like this?
edit: I just realized that my question may be misconstrued as creating a NEW instance of the object. I have already created the instance, and i wish to get the existing instance of the class
As many others have noted in the comments, what you are trying to do is not possible with static methods. Also, you should try to avoid static methods whenever possible because they can result in a testing and maintanance nightmare (*).
You named your method "getInstance", so I guess what you want to do is a mix of Factory- and Singleton patterns. Here is some information to get you started about these patterns:
Singleton: http://en.wikipedia.org/wiki/Singleton_pattern
Factory Method: http://en.wikipedia.org/wiki/Factory_method_pattern
Abstract Factory: http://en.wikipedia.org/wiki/Abstract_factory
Both should not be coded by hand in these days (*) - Have a look at a good "Dependency Injection" (DI) container like Google Guice or Spring. I am not 100% sure what exactly you want to achieve, but it looks like a DI container will do it for you.
Edit: This is a response to an edit of the question. You want to receive a cached instance of the sub classes. In this case, I would still advise against static methods. You could create a singleton instance of a "BCache" class (using a DI container or programming it by hand), and then use this cache object to look up your registered objects. Using Guice as a DI container, it could look like this (warning, untested):
#Singleton
public class BCache {
private Map<Class<? extends B>, B> cache = ...;
public <T> T getInstance(Class<? extends T> type) {
return (T) cache.get(type);
}
}
I still think it would be possible to get rid of the cache class completely using a DI container, though. Again, this is untested code, using Guice, but it could look like this:
#Singleton
public class A extends B {
public A() {
//I am not sure if you need to register in this case, because your
//DI container keeps track of the singleton instances.
super.register(this);
}
}
public class SomeClassUsingA {
#Inject private A a;
}
(*) Note that "all generalizations are wrong", that is, in some projects it might make sense, but in most it will not.
You can't do exactly what you want with the static methods, in good OOP way. You can can do something with the reflection or bunch of if .. else if.
You however, should use some well defined design patterns like Abstract fectory or Factory method. This is the way you should go, like someone said "Don't invent warm water".
You can always assign a subClass instance to a superClass reference. Therefore your superClass's static methods can set or get a subClass instance. But make sure to cast the returned instance before using.
public class A {
private static A a;
/**
* #param a the a to set
*/
public static void setA(A a) {
A.a = a;
}
/**
* #return the a
*/
public static A getA() {
return a;
}
public class B extends A {
private int index = 0;
/**
* #param index the index to set
*/
public void setIndex(int index) {
this.index = index;
}
/**
* #return the index
*/
public int getIndex() {
return index;
}
Usage:
public static void main(String[] args) throws Exception {
B b = new B();
A.setA(b);
B c = (B) A.getA();
System.out.println(c.getIndex());
}
Change form getInstance() to getInstance(String class)
in the superclass:
public static A getInstance(String class){
if(class.equals("A")){
RegisterObject(...);//User defined method
return new A(...);
}
else if(class.equals("B")){
RegisterObject(...);//User defined method
return new B(...);
}
else if(class.equals("C")){
RegisterObject(...);//User defined method
return new C(...);
}
//... and so on
}
Static methods are cannot know which class is used to invoke them. If for example you have class A and B that extends A and static getInstance() implemented in A there is no difference whether you invoke getInstance() using A or B. Moreover attempt to call B.getIntance() will produce compilation warning (at least in Eclipse).
However you can pass the class as a parameter of getInstance():
public class A {
public static <T extends A> T getInstance(Class<T> clazz) {
return clazz.newInstance(); // I do not catch exceptions here: do it yourself
}
}
public class B extends A {
}
...............
B b = A.getInstance(B.class);
You can do like this way,
class A{
public static A getInstance(){
return new A();
}
#Override
public String toString() {
return "inside A";
}
}
class B extends A{
public static A getInstance(){
return new B();
}
#Override
public String toString() {
return "inside B";
}
}
inside main :
public static void main(String[] args) {
A a1 = A.getInstance();
A a2 = B.getInstance();
System.out.println(a1.toString());
System.out.println(a2.toString());
}

Creating instance in java class

Please advise me the difference between two ways of declaration of java constructor
public class A{
private static A instance = new A();
public static A getInstance() { return instance;
}
public static void main(String[] args) {
A a= A.getInstance();
}
}
AND
public class B{
public B(){};
public static void main(String[] args) {
B b= new B();
}
}
Thanks
Class A is supposed to be a Singleton, where you can only have one instance of A. You retrieve that single instance by calling getInstance();
In software engineering, the singleton
pattern is a design pattern used to
implement the mathematical concept of
a singleton, by restricting the
instantiation of a class to one
object. This is useful when exactly
one object is needed to coordinate
actions across the system.
There are a few ways to go about this depending on your requirements:
public class A{
private static A instance = new A();
private A(){} // private constructor
public static A getInstance() {return instance;}
}
or not creating the instance until the first call
public class A{
private static A instance = null;
private A(){} // private constructor
public static A getInstance() {
if(instance == null){
instance = new A(); // create the one instance.
}
return instance;
}
}
Class B is a class with a no-parameter constructor. You can create as many B instances as you want by calling new B();
It looks like A is an attempt at implementing the singleton pattern, but it's not quite right - it should have a private constructor:
class A {
private static final A INSTANCE = new A();
private A() { }
public static A getInstance() { return INSTANCE; }
}
This ensures that only one instance of A ever exists in your application - if any other object needs to use an instance of A to do something, the only way it can get one is via the getInstance() method, which returns the same instance all the time.
With B, you can have as many instances of B as needed/desired, and any other object is free to make a new instance of B if it chooses.
In the first case, only one instance available. In the second case, one can have as many as possible. You need to make the constructor private in the in the first case.

Categories

Resources