How to avoid the creation of object in Java? - java

I am new to java programming,I have one class,for this class i created two object(obj1,obj2).i don't want to create other than these object,if any body wants to create one more object for this class that should refer to first,or second objects only(instead of creating one more object).how to do this?please refer below code
class B
{
void mymethod()
{
System.out.println("B class method");
}
}
class Myclass extends B
{
public static void main(String s[])
{
B obj1=new B();//this is obj1
B obj2=new B();//this is obj1
B obj3=new B();//don't allow to create this and refer this to obj1 or obj2
}
}
Thanks
azam

Check out the Singleton design pattern.

What you need is the Singleton design pattern.
Class B should look something like so:
class B
{
private static B instance = null;
private B()
{
//Do any other initialization here
}
public static B getInstance()
{
if (instance == null)
{
instance = new B();
}
return instance;
}
}
Then, in your Myclass, just do this:
B obj1 = B.getInstance();
B obj2 = B.getInstance();
Note: This is not thread safe. If you are looking for a thread safe solution please consult the Wiki Page.
EDIT: You could also have a static initializer
class B
{
private static B instance = null;
static
{
instance = new B();
}
private B()
{
//Do any other initialization here
}
public static B getInstance()
{
return instance;
}
}

Yeah singleton it seems the correct way consider the info your providing here.
The default singleton implementation would be the following:
public class Singleton {
//holds single instance reference
private static Singleton instance = null;
//private constructor to avoid clients to call new on it
private Singleton()
{}
public static Singleton getInstance()
{
if(null == instance)
{
instance = new Singleton();
}
return instance;
}
}
Now you can get the single instance of the object by calling :
Singleton instance = Singleton.getInstance();
Keep in mind though that if your working on a threaded enviroment, singleton by default is not thread-safe.
You should make the getInstance method synchronized to avoid unexpected returns.
public synchronized static Singleton getInstance()
{
if(null == instance)
{
instance = new Singleton();
}
return instance;
}
Cheers

Generally speaking you need a singleton pattern. You need to make the constructor to become a private method. Then you create a method to instantiate class B, hence class B can only be instantiated by this method. Have a look at the singleton pattern. It is what you want I believe.

create singleton Class, like
public Class A {
private static Class a = new A();
public A getA() {
return a;
}
}
Object of class A has already created in class A itself. You don't need to create it outside. Just use getA() method to retieve the class A's object.
Like :
A objA = A.getA();
This is called Singlton Pattern.

You can use a Singleton. You have 2 possiblilities for that.
1 . Lazy Creation (Here you make the instance when call the function getInstance() and you check if the instance already exists):
class B {
static private B instance;
private void mymethod() {
System.out.println("B class method");
}
static public B getInstance() {
if (instance == null) {
instance = new B();
}
return instance;
}
}
class Myclass extends B {
public static void main(String s[]) {
B obj1 = B.getInstance(); // this is obj1
B obj2 = B.getInstance();
}
}
2 . Eager creation (Here you make the instance when the Class is called for the first time):
class B {
static private B instance = new B();
private void mymethod() {
System.out.println("B class method");
}
static public B getInstance() {
return instance;
}
}
class Myclass extends B {
public static void main(String s[]) {
B obj1 = B.getInstance(); // this is obj1
B obj2 = B.getInstance();
}
}

be aware, that using a singleton is a big restriction to your code. It can be very annoying when it's not possible to instance more than one object.
Especially when you dont have acces to the source....

The Effective way in multi threaded application, the below logic will may help
public class Singleton {
private static volatile Singleton _instance;
private Singleton(){}
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}

I suppose people have not understood the problem statement. It says, not more than 2 objects shall be created. Singleton creates a single object and blocks any further instantiation.
maintain a static variable in ur object class, incrementing by 1 to the upper limit of objects while creating object
when object > bounds needs to be created, select a random number in range[1,bound] and return that object.

Related

Restrict a class for creating second object in java

Is there a way where we can restrict a class to create only a single object in java? It should give some exceptions if we try to create another new object.
Example:
class A {}
public class Test {
public static void main(String[] args) {
A a1 =new A(); //This should be allowed
A a2 =new A(); // This should not be allowed
}
}
to try your additional requirement:
This should work, but I don't really see a point to it.
public class A {
private static boolean instantiated;
public A() throws Exception {
if ( instantiated ) {
throw new Exception("Already instantiated");
}
instantiated = true;
}
}
You can use the special Singleton pattern. Most of the examples are on the internet.
public class Singleton {
private static Singleton instance;
public static synchronized Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}

Stack overflow created by a cycle in code with singletons

I have two singleton classes, lets call them class A and class B.
The classes look like such.
class A
{
private static A instance;
private A(int timeout)
{
init();
}
public static A getInstance(int timeout)
{
if(instance == null)
{
instance = new A(timeout);
}
return instance;
}
private void init()
{
new Monitor().sendMonitorStatus();
}
}
and for class B
class B
{
private static B instance;
private B(A a)
{
}
public static B getInstance(A a)
{
if(instance == null)
{
instance = new B(a);
}
return instance;
}
}
Then there is a class named Monitor as well that looks as such.
class Monitor
{
public void sendMonitorStatus()
{
B.getinstance(A.getinstance(10));
}
}
The problem as you can see, is that I get a stackoverflow since it keeps a cycle of a call to B then calling A which calls B which calls A..., is there anyway to solve this problem without a redesign or is the only way to solve this cycle causing this error to redesign how the classes work?
To create an instance of A, you need to call Monitor::sendMonitorStatus. To call Monitor::sendMonitorStatus, you need an instance of A. You have a dependency cycle.
You need to redesign this. Exactly how – it depends on what you want to achieve.

Java Singleton has different toString() value

I have a classic singleton implemented in java
public class ClassicSingleton {
private static ClassicSingleton instance = null;
private ClassicSingleton() {} ;
public static ClassicSingleton getInstance() {
if (instance == null)
return new ClassicSingleton();
return instance;
}
}
I have the following driver
public class SingletonDriver {
public static void main(String[] args) {
System.out.println(ClassicSingleton.getInstance().toString());
System.out.println(ClassicSingleton.getInstance().toString());
}
}
The output is something like
ClassicSingleton#75e4f66a
ClassicSingleton#aede59e
I thought the output would be pointing to the same object. Shouldn't the values be the same?
Your implementation of getInstance() is wrong. You never initialize instance, and thus return a new instance on each invocation. If instance is null, you should save it to your data member, and only then return it:
public static ClassicSingleton getInstance() {
if (instance == null)
instance = new ClassicSingleton();
return instance;
}
You forgot to assign new ClassicSingleton() to instance, so you actually have a factory instead of a singleton; you'll create a new instance on every call. (Note also, of course, that this isn't thread-safe.)

how to create an instance of a class to access through the application

i have a util class where which don't have access to session object. i want to initialize this util class only once while login and want to get that instance throughout application.
Here every user need to have his own instance of that util class how to achieve this.
please help me
are you looking for Singleton Pattern ??
private static MyClass instance;
private MyClass(){}
public static MyClass getInstance() {
if (instance != null) {
return instance;
} else {
return new MyClass();
}
}
public static void setInstance(MyClass inst) {
instance = inst;
}
How about using the factory pattern. Then you can pass parameters to the factory method and return a new instance for each user.
I agree with #GanGnaMStYleOverFlow about singleton, but want to provide better version of its implementation:
public class MyClass {
private static MyClass instance;
private MyClass() {}
public static synchronized MyClass getInstance() {
if (instance != null) {
instance = new MyClass();
}
return new MyClass();
}
}
This class cannot be instantiated directly because constructor is private. You cannot create 2 instances of this class because it is managed by getInstance(). This implementation is threadsafe because getInstance() is synchronized.

Singleton class Identification

Can anyone please tell me whether this is a singleton class or not?
public class Final_output{
Cafe_factory obj=null;
private Final_output()
{
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public static void main(String args[])
{
new Final_output();
}
}
Cafe_factory is another class in the same package.
This is not a Singleton.
Singleton for Example is:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Not, it's not. Because you can't create instances of this class outside of it (at least one instance should exist). For the other hand - you can create as many instances inside main as you wish (so it's not singleton either).
Here is an example of Singleton:
public class MySingleton{
private MySingleton(){}
private static InstanceHolder{
private static final MySingleton instance = new MySingleton();
}
public static MySingleton getInstance(){
return InstanceHolder.instance;
}
}
Its not.
A singleton has as objective to limit to 1 the number of instances of the same class that can be created, and provide static methods to retrieve this instance.
This is typically done via a private constructor and static methods to retrieve this unique instance. Here neither Final_output nor Cafe_factory respect this contract so none of them use the singleton pattern.
Since you could create n amount of new Cafe_Factory objects in your code also outside the Final_output class, no it is not a singleton. A singleton is never created with the new keyword. Instead, you fetch an instance of it via a static method.
this :
public class Final_output{
private static Cafe_factory obj = null;
private Final_output()
{
obj = getCafeInstance();
}
public static getCafeInstance(){
if(null == obj){
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}else{
return obj;
}
}
}
NO This is not a singleTon
public class Final_output{
private static Final_output ourInstance = new Final_output();
Cafe_factory obj=null;
private Final_output() {
obj = new Cafe_factory();
obj.getOrder("French Fries");
obj.getOrder("Biryani");
obj.getOrder("Ice-cream");
}
public Final_output getINstance(){
return ourInstance;
}
}

Categories