Basically I have a class which an instance of is created via a Singleton class. The class should never been instantiated via any other means than the singleton class. My question is can the class be effectively 'not seen' by other classes, apart from Singleton.
I know inner classes and different pacakages etc would help, but I'm curious to see if anyone has a nice solution to this.
Thanks for replies
Just refactor class itself as singleton. Private constructor and etc.
An easy and efficient way to do Singleton with an Enum:
public enum Singleton {
INSTANCE;
public void execute (String arg) {
//... perform operation here ...
}
}
In a sample scenario, using your API, do I need to declare?:
ToBeInvisibleClass instance = TheSingleton.getThatInvisibleInstnace();
If the answer is Yes, then the answer to your question is No since I need to declare a variable and for that I need the type to visible. If the answer is No, then using inner/nested class seems to be a proper approach or making the class itself the singleton.
Java has no "friend" concept like C++
You mentioned nested classes (real inner classes will not work because they need the outer) and packages.
Other approaches to protected other classes but one from creating an instance are not known to me.
But in general there is no reason to build a singleton by an helper class.
You could build singleton using enums or static final vars
What is the best approach for using an Enum as a singleton in Java?
public enum Elvis implements HasAge {
INSTANCE;
private int age;
#Override
public int getAge() {
return age;
}
}
class X {
public static final X instance = new X ();
private X () {
}
...
}
To assure that instantiation only occurs through your class method, you can do the following:
Make the default constructor private
Save your singleton instance in a private method
Use a public static method to provide the instance to the clients:
In this site there's a nice example:
public class MySingleton {
private static MySingleton _instance = new MySingleton();
private MySingleton() {
// construct object . . .
}
public static MySingleton getInstance() {
return _instance;
}
Related
I learned that static methods are used to create an instance of a class type. I see that some classes using static method have to declare a private constructor for that class.
What is the use of private constructor? Can we still create an instance of a class without using the private constructor? Thanks.
Basically we use this kind of static factory method in Singleton Design Pattern.
Singleton means based on this design pattern we can create only one object for the class.
for Example:
class Test{
private static Test mObject;
private Test()
{
}
public static Test getInstance(){
if(mObject==null){
mObject=new Test();
}
return mObject;
}
}
What is the use of Private Constructor?
If a class has only private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class
Can we still create an instance of a class without using Private
Constructor
Yes using reflection (need to call setAccessible of constructor)
I'm a begginer programmer for Android and I found some code over the internet and I couldn't get what this "Class not meant to be instantiated" means?! Also what's the use of it. I would be very happy if somebody could help here.
public class Settings
{
//some code
private Settings() {} // Class not meant to be instantiated
//some code
}
The constructor is private so only the class itself can create instances. There are several reasons for doing this. A couple off the top of my head...
The class is a "utility" class that only contains static methods and so instantiating it would make no sense. As the class is commented "Class not meant to be instantiated" I guess this is the most likely reason.
The class itself controls its own lifecycle and provides methods for creating instances. For example if the class is a lazy singleton it might provide a method that creates an instance when first called and return this instance on subsequent calls.
It is a private constructor. This means that outside classes cannot create new instances using the default constructor.
A little more info
All Objects in Java have a default constructor:
public MyObject() {}
That is how you can have this class:
public class MyObject{}
and still be able to call:
MyObject mObj = new MyObject();
Private Constructors
Sometimes a developer may not want this default constructor to be visible. Adding any other constructor will nullify this constructor. This can either be a declared constructor with empty parameters (with any of the visibility modifiers) or it can be a different constructor all together.
In the case above, it is likely that one of the following models is followed:
The Settings object is instantiated within the Settings class, and is where all the code is run (a common model for Java - where such a class would also contain a static main(String[] args) method).
The Settings object has other, public constructors.
The Settings object is a Singleton, whereby one static instance of the Settings Object is provided to Objects through an accessor method. For example:
public class MyObject {
private static MyObject instance;
private MyObject(){}//overrides the default constructor
public static MyObject sharedMyObject() {
if (instance == null)
instance = new MyObject();//calls the private constructor
return instance;
}
}
This inner construct
private Settings() {}
is a constructor for Settings instances. Since it is private, nobody can access it (outside of the class itself) and therefore no instances can be created.
The constructor is private so its not meant to be called by anything outside of the class
It's not a nested class, it's a constructor. A private constructor means that you can't construct instances of this class from outside, like this:
Settings s = new Settings(); //Compilation error! :(
Now, if a class can't be instantiated, what could it be for? The most likely reason for this is that the class would return instances of itself from a static method, probably as a singleton. The settings are normally global to the program, so a singleton pattern really fits here. So there would be a static method that goes kind of like this
static private TheOnlySettings = null;
static public getSettings()
{
if(TheOnlySettings == null)
TheOnlySettings = new Settings(); //Legal, since it's inside the Settings class
return TheOnlySettings;
}
See if that's indeed the case.
As other have mentioned, a class having private constructors cannot be instantiated from outside the class. A static method can be used in this case.
class Demo
{
private Demo()
{
}
static void createObjects()
{
Demo o = new Demo();
}
}
class Test
{
public static void main (String ...ar)
{
Demo.createObjects();
}
}
We can have private constructor . Below program depicts the use of private constructor with a static function
class PrivateConstructor {
private:
PrivateConstructor(){
cout << "constructor called" << endl;
}
public:
static void display() {
PrivateConstructor();
}
};
int main() {
PrivateConstructor::display();
}
The standard method of implementing singleton design pattern is this:
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
private Singleton() {}
}
I was wondering if you could also implement it like this:
public class Singleton {
private Singleton() {}
public final static Singleton INSTANCE = new Singleton();
}
and if yes which version is better?
Neither. In both cases, a trusted consumer can invoke the private constructor via reflection. An additional problem is that it these implementation don't play nicely with serialization unless you take extra steps to make it so (by default, if you take the naïve approach, every time a Singleton is deserialized, it will create a new instance).
The correct solution is to use an enum that defines a single value.
public enum Singleton {
INSTANCE;
// methods
}
From Effective Java:
While this approach is yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
Why you not use enum for realisation Singleton?
public enum SingletonEnum {
Instance;
private static String testStr = "";
public static void setTestStr(String newTestStr) {
testStr = newTestStr;
}
public static String getTestStr() {
return testStr;
}
public static String sayHello(String name) {
return "Hello " + name;
}
}
In my opinion first one is better as it looks more aligned to Object oriented approach.
While there's nothing particularly wrong with either solution, this solution from Wikipedia should give you the best compatibility and give you a thread-safe singleton:
University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[11] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.
The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:
public abstract class MessageBase {
protected DAOFactory factory;
// method declarations
}
public class EDWMessage extends MessageBase {
private static MessageBase instance;
public static MessageBase getInstance(Properties properties) {
if (instance == null) {
instance = new EDWMessageTransaction(properties, null);
}
return instance;
}
//more code
}
I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?
The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!
P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.
Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.
This is a common idiom for thread-safe lazy singleton initialization. If you can have a singleton class, you delegate to a private static instantiating class.
public class MySingleton{
private MySingleton(){
}
public static MySingleton getInstance(){
return SingletonCreator.INSTANCE;
}
private static class SingletonCreator{
private static final MySingleton INSTNACE = new MySingleton();
}
}
Not sure if this is how your child class is being used, but this would be a use case for a child class holding a static instance of its parent
The original intent probably was that for each subclass of MessageBase there should only be 1 instance and that you can access that instance with a commom method in the base class
so you could iterate over all message types and get the instance of each
my 2cents
By design, in Singleton pattern the constructor should be marked private and provide a creational method retuning the private static member of the same type instance. I have created my singleton classes like this only.
public class SingletonPattern {// singleton class
private static SingletonPattern pattern = new SingletonPattern();
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
return pattern;
}
}
Now, I have got to extend a singleton class to add new behaviors. But the private constructor is not letting be define the child class. I was thinking to change the default constructor to protected constructor for the singleton base class.
What can be problems, if I define my constructors to be protected?
Looking for expert views....
If you extend a singleton class via inheritance, you'll have 2 instances of the singleton class running around should someone grab your singleton and the original singleton.
If the original singleton is conceptually really supposed to be a singleton, then using composition is probably the way to go. However, then substitutability is lost (your class is not substitutable for the original singleton; it just uses it).
Do you have a concrete example?
If you do that, it's not a singleton. But perhaps you don't really need a singleton.
This is not the Singleton Class. Imagine I can call getInstance() static method n number of times and I can have n objects of this class thus completely violating Singleton Pattern. To make it Singleton you should check whether object is already created or not in getInstance() method. If already created then you should ignore and do not create again. For example, you can so something similar, please ignore syntax mistakes, just a code to explain, can vary in different languages.
public class SingletonPattern {// singleton class
private static SingletonPattern pattern = new SingletonPattern();
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
if(SingletonPattern == null) {
return new SingletonPattern();
}
}
Old question I know but happened to stumble upon this and think I can add something useful.
It is possible to have a protected constructor in a singleton class. If you want to have polymorphic behavior on your Singleton you can make it an abstract class, set the constructor to protected and delegate creation of the instance to one of the concrete sub classes.
I found the following example in the book "Design Patterns explained":
abstract public class Tax{
static private Tax instance;
protected Tax() {};
abstract double calcTax( double qty, double price);
public static Tax getInstance() {
// code to determine what implementing class to use
instance = USTax.getInstance();
return instance;
}
}
public class USTax extends Tax {
private static USTax instance;
private USTax() {
// instantation local members + Tax abstract class
}
public double calcTax ( double qty, double price){
// implementation
}
public static Tax getInstance() {
if(instance == null)
instance = new USTax();
return instance;
}
}