I can still instantiate by using constructor although in class definition it has been declared as private constructor??? Here is code snippet:
public class Singleton {
private static Singleton instance;
private String name;
/* Private constructor prevents other classes from instantiating */
private Singleton(String name) {
this.name = name;
// Optional code
}
/*
* Static factory method that creates instance instead of constructor.
* Synchronization helps to block any attempt to instantiate from simultaneous
* thread hence break concept of singleton.
* This method uses a technique known as lazy instantiation.
*/
public static synchronized Singleton getInstance(String name) {
if (instance == null) {
instance = new Singleton(name);
}
return instance;
}
/* Override Object clone method to avoid cloning */
#Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public String getName() {
return name;
}
/* Example of using singleton object */
public static void main(String[] args) {
Singleton a = new Singleton("Hoang");
Singleton b = new Singleton("Shiha");
System.out.println(a.getName());
System.out.println(b.getName());
}
You can still instantiate it because your test main() method, being in the same class, has access to the private constructor: private means "only available to this class".
Put your test in another class, and you'll get what you expect.
Your test method is within the same class -> it has access to private members & methods.
Refer to this question for more info on the Singleton pattern in Java :)
You are able to instantiate the singleton because you are doing it from a method inside the Singleton's class definition (hint, you can access private methods within the class that define them.
Try doing that from outside your Singleton, and it will fail. On another note, Singleton are typically defined as final (very rare that you legitimately need to extend a Singleton class).
On another note, one typically puts some sort of guard condition (.ie. throwing a UnsupportedOperationException) on the default (and private) constructor to defend against accidental (or malicious attack) access to it via reflection.
/* default constructor made private and defended against reflection access */
private Singleton() {
throw new UnsupportedOperationException("naughty boy");
}
To be sure to instanciate it just once, you may use the Singleton Enum pattern:
public enum MySingleton {
INSTANCE("My singleton name");
private MySingleton(String name) {
this.name = name;
}
private String name;
public String getName() {
return this.name;
}
}
An enum is in some way a list of singletons sharing the same interface
Related
This answer says that we can't instantiate more than one object at a time via private constructors. I have modified the code which does just the opposite:
class RunDatabase{
public static void main(String[] args){
Database db = Database.getInstance("hello");//Only one object can be instantiated at a time
System.out.println(db.getName());
Database db1 = Database.getInstance("helloDKVBAKHVBIVHAEFIHB");
System.out.println(db1.getName());
}
}
class Database {
//private static Database singleObject;
private int record;
private String name;
private Database(String n) {
name = n;
record = 0;
}
public static synchronized Database getInstance(String n) {
/*if (singleObject == null) {
Database singleObject = new Database(n);
}
return singleObject;*/
return new Database(n);
}
public void doSomething() {
System.out.println("Hello StackOverflow.");
}
public String getName() {
return name;
}
}
And as expected both the strings are being printed. Did I miss something?
We can't instantiate more than one object at a time via private constructors.
No, we can. A private constructor only avoids instance creation outside the class. Therefore, you are responsible for deciding in which cases a new object should be created.
And as expected both the strings are being printed. Did I miss something?
You are creating a new instance every time the getInstance method is called. But your commented code contains a standard lazy initialization implementation of the singleton pattern. Uncomment these parts to see the difference.
Other singleton implementations you can look over here.
Private constructors are used to stop other classes from creating an object of the "Class" which contains the private constructor.
This is done to provide the singleton pattern where only a single instance of the class is used.
The code that you have mentioned is supposed to create just one instance of the class and use that instance only to perform all the operations of that class. But you have modified the code which violates the singleton design pattern.
Why do we need a private constructor at all?
Basically 3 reasons:
if you don't want the user of the class creates an object directly, and instead use builders or similars,
if you have a class defined for constants only, then you need to seal the class so the JVM don't create instances of the class for you at runtime.
singletons
A friend of mine just brought up that I should use getters for classes, is this considered good practice or not? I couldn't find the answer elsewhere.
And how about Setters for classes? Does that even exist?
Thanks for your input.
public class Movement {
private Player p;
public Movement(Player p) {
this.player = p;
}
// methods
}
public class Player {
/**
* The movement class that handles all players movements
*/
private Movement movement;
public Player() {
this.movement = new Movement(this);
}
public Movement getMovement() {
return this.movement;
}
}
#people saying duplicate question
This is not simple variables that require protection by being private.
This is about the habit of adding a getter for a class, which I don't get since the class is already public.
And how about Setters for classes? Does that even exist?
AFAIK, not in Java. Whenever you want to modify class properties or behaviour, you change its members or methods respectively (by "setter" methods in some cases, yes), or you provide another constructor to a class to create some specified instance of it.
The point of getters and setters is to provide encapsulation concept, which is used, mainly, to restrict or configure access to some of the certain object's components (not the whole class instance itself).
As for classes, in Java we have access modifiers for the same reason.
My guess is that your friend may talk about something like Singleton pattern in which you're actually using some kind of "getter" method to get access to class instance like in here:
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) { //That's what you are probably asking about
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
Or it's about static factory pattern given as example in this answer.
Summary: Despite the fact that the class itself is public, there's no public constructors availiable, so this is the reason to provide some kind of a "getter". So this is your case, I suppose.
Getter and setter are used to hide/protect private/protected variable from
other Classes. Exemple:
Class Person{
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
I don't see any difference between setting a member variable versus setting a object. You can set the value for an object in same was as you set the member variables.
public void setPlayer(Player player){
this.player = player;
}
public Player getPlayer(){
return player;
}
public void setMovement(Movement movement){
this.movement = movement;
}
public Movement getMovement(){
return movement;
}
If you don't want to set the object value explicitly, you can set the value in constructor and provide only getter method to callers so that no one else can set the value except by calling constructor. Even if you do not want to call constructor for setting the value, create Singleton class by making constructor as private. I hope you know how to create Singleton classes
I have an object say A that loads some data from disk and it takes a bit long time to load. Many of other objects need its methods and data so I don't want neither any time I need it create a new one nor passing it through class constructor. Is there any way to create an instance of the class A only once at the beginning of the running project and all the other objects have access to the object A?
I apologize if my question is duplicated but I don't have any idea about what keywords relate to this question to find related questions.
In that case you are dealing with the Singleton Design Pattern you should declare youre class like this:
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
And then you can use it as intended.
In fact the approach here is to use static members like this:
public class Vehicle {
private static String vehicleType;
public static String getVehicleType(){
return vehicleType;
}
}
The static modifier allows us to access the variable vehicleType and the method getVehicleType() using the class name itself, as follows:
Vehicle.vehicleType
Vehicle.getVehicleType()
Take a look at Java static class Example for further information.
Sure. The design pattern is called a singleton. It could look like this:
public class Singleton {
private static Singleton instance;
private Singleton () {}
/*
* Returns the single object instance to every
* caller. This is how you can access the singleton
* object in your whole application
*/
public static Singleton getInstance () {
if (Singleton.instance == null) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
All objects can use the singleton by calling Singleton.getInstance()
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();
}
}
I need a singleton in my code. I implemented it in Java and it works well. The reason I did it, is to ensure that in a mulitple environment, there is only one instance of this class.
But now I want to test my Singleton object locally with a Unit test. For this reason I need to simulate another instance of this Singleton (the object that would be from another device). So is there a possiblity to instantiate a Singleton a second time for testing purpose or do I have to mock it?
I'm not sure, but I think it could be possible by using a different class loader?
Traditionally, a Singleton creates its own instance, and it creates it only once. In this case it is not possible to create a second instance.
If you use Dependency Injection, you can let the framework create the singleton for you. The singleton does not guard against other instances (i.e. it has a public constructor), but the dependency injection framework instantiates only one instance. In this case, you can create more instances for testing, and your object is not cluttered with singleton code.
The point of a Singleton is that you can only instantiate it once.
You can invoke the private constructor of your singleton class using reflection to create a new instance of the class.
class MySingleton {
private MySingleton() {
}
}
class Test {
public void test() throws Exception {
Constructor<MySingleton> constructor = MySingleton.class.getConstructor();
constructor.setAccessible(true);
MySingleton otherSingleton = constructor.newInstance();
}
}
A singleton, by definition, can only be instantiated once. However, the fact that your unit test requires two singletons is a strong indication that your object shouldn't really be a singleton, and that you should rethink the singleton design.
I feel compelled to post this series of articles about how Singletons destroy testability and are poor design choices:
Singletons are Pathological Liars
Where Have All the Singletons Gone?
Root Cause of Singletons
Short summary: combining logic for what a class does with how it is instantiated makes code that is ugly to test, and should be avoided.
First, why do you need to create a new singleton to run a unit test? A unit test should not be running concurrently with the normal application, so you should be able to access the original singleton without fear of modifying it..
Is there a particular reason you need an explicit second singleton?
you could just make another static method getInstance2 that looks like this:
class MySingleton
{
private MySingleton(){}
private static MySingleton instance1 = new MySingleton();
private static MySingleton instance2 = new MySingleton();
public static MySingleton getInstance(){ return instance1; }
public static MySingleton getInstance2(){ return instance2; }
}
Singleton ston=Singleton.getInstance(); will return singleton object. By making use of "ston" object, if we call the method createNewSingleTonInstance() which is written in Singleton class will give new instance.
public class Singleton {
private String userName;
private String Password;
private static Singleton firstInstance=null;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(firstInstance==null){
firstInstance=new Singleton();
firstInstance.setUserName("Prathap");
firstInstance.setPassword("Mandya");
}
return firstInstance;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
Password = password;
}
public String getPassword() {
return Password;
}
public Singleton createNewSingleTonInstance(){
Singleton s=new Singleton();
s.setUserName("ASDF");
s.setPassword("QWER");
return s;
}
}
You may keep a key on a map and populate instance with key
public class MultiSingleton {
/**** Non-static Global Variables ***/
String status = "";
private BaseSmartCard bsc;
/***********************************/
private static Object lockObject = new Object();
private String serialNo;
private static Map<String, MultiSingleton> mappedObjects = new TreeMap<String, MultiSingleton>();
protected MultiSingleton() {
}
public static MultiSingleton getInstance(String serialNo,long slotNo){
if (mappedObjects.isEmpty() || !mappedObjects.containsKey(serialNo)) {
MultiSingleton instance = new MultiSingleton();
instance.setSerialNo(serialNo);
mappedObjects.put(serialNo, instance);
return instance;
} else if (mappedObjects.containsKey(serialNo)) {
return mappedObjects.get(serialNo);
}else {
return null;
}
}