alternative solutions for Static Methods And Singleton in java database - java

i Want to make a class and some methods in that class which interact with database.
Many other classes Should call that methods.
Q1:is it possible to create only one instance of that class for others ?
Q2:Can i give methods as Static?
Q3:Is there is any alternative solution for static and singleton for java database?

I have not used singletons in Java yet. However, there's a pretty good discussion on the subject at http://c2.com/cgi/wiki?JavaSingleton
Basically, you will make your constructor private along with a private static final instance variable. Then you will need a public static getInstance method that returns your instance. It gets a bit more complicated if you need to be thread safe, so read the linked article.

You can also use an enum with a single variable INSTANCE like below:
public enum EmployeeDAO {
INSTANCE;
static{
//Initialize connection info etc.
init();
}
private EmployeeDAO(){
//Constructor stuff
}
public Employee getEmployeesById(int id){
//Replace this with your data retrieval logic
return null;
}
public Employee getDeadBeatEmployees(){
//Replace this with your data retrieval logic
return null;
}
public Employee getAllStars(){
//Replace this with your data retrieval logic
return null;
}
public static void init(){
}
}
public class Employee{}
public class SillyCanuck{
public static void main(String args[]){
EmployeeDAO.INSTANCE.getEmployeeById(5);
}
}

Related

Why do we need a private constructor at all?

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

How to access an specific object from other object without passing pointer to that object in java?

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()

How do you mock a method which uses a private static inner class as a parameter?

I have a class with a method that takes a single parameter. This parameter is a nested class inside the mocked class, but it is private (And static but I don't think that makes much of a difference to this). How do I go about mocking this method?
Example:
public class myClass {
public anotherObject;
public myClass(AnotherObject anotherObject) {
this.anotherObject = anotherObject;
}
public void exec() {
//Some instructions ...
//This second method is inside another completely seperate class.
anotherObject.secondMethod(new NestedClass());
}
private static class NestedClass {
public NestedClass() {
//Constructor
}
//Variables and methods, you get the picture
}
}
In the above example secondMethod(...) is the method that I want to mock.
All attempts to find other examples of this problem just return results relating to mocking a single private nested class, or mocking static classes, which aren't completely relevant to this and don't seem to provide any work around that I can figure out.
EDIT:
I'm looking for some sort of solution that looks like this:
#Test
public void testExec() {
AnotherObject anotherObject = mock(AnotherObject.class);
when(anotherObject.secondMethod(any(NestedClass.class))).thenReturn(0);
MyClass testThisClass = new MyClass(anotherObject);
}
Notes: I'm not allowed to make modifications to the code I'm afraid, I am only allowed to create these tests to make sure the current implementation works later down the line when modification are made to it.
If I am understanding the requirement correctly, add one method say executeSecondMethod(). Call this method in your main method class.
public class myClass {
public void exec() {
//Some instructions ...
secondMethod(new NestedClass());
}
public void secondMethod(NestedClass example) {
//Some instructions that I want to just mock out...
}
private static class NestedClass {
//Variables and methods, you get the picture
}
public static executeSecondMethod(){
secondMethod(new NestedClass()); // pass the nested class object here
}
}
public class mainClass{
public static void main(){
executeSecondMethod();
}
}

Java - make class static instead of one instance of it

Let's say i have a class, and I made only one instance of it and i don't need more than that.
Should i just make the class static ? (not the class itself but the functions and the variables).
In the example below should i make the class static if i won't make more than one instance of it ?
public class Foo {
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = new Foo(); //I don't need more than one instance of that class.
}
If your class has no state, say:
class NoState {
static int sum(int i1, int i2) { return i1 + i2; }
}
then it makes sense to use static methods.
If you must ensure that there is only one instance of your class, then you could use a singleton, but be careful: global state can be evil.
Not as bad as a singleton, you could use static fields/methods: it can be useful is some situations but should not be abused.
In any other situations (= most of the time), just use normal instance variables/methods.
You can use an enum to define a singleton.
public enum Foo {
INSTANCE;
int num1;
int num2;
public void func() {
// Something in here
}
}
public static void main(String[] args) {
Foo bar = Foo.INSTANCE;
}
However, this is only need if you want to enforce one instance. Otherwise, I would just use new Foo(); and call it only once, if you only need one.
You can use Singleton. However, make sure if Singleton is what is really required - sometimes singletons gets overused where simple class with static methods might suffice. There are many ways to create singleton as explained What is an efficient way to implement a singleton pattern in Java?
Note that with Java 5, enum is the preferred way to create singleton.
You say that i don't need more than that so my answer is that not make more than one and if you really like to enforce the instance that it should be only one for class then use the enum best way to implement the singleton in java
for example in datasource one really needs singleton
public enum UserActivity {
INSTANCE;
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private UserActivity() {
this.dataSource = MysqlDb.getInstance().getDataSource();
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public void dostuff() {
...
}
}
and if you really need that then use it otherwise go with your current logic
A class that must be instantiated once and only once, is called a singleton. That knowledge should help you narrow down your search for information. To give you a head start:
Difference between static class and singleton pattern?
Why use a singleton instead of static methods?
Basically static methods and fields means that you don't need any instances of the class.
In you case you need 'singleton' class, you can either use enum or make it a singleton by yourself, using the specific set of rules.
It really depends on the scope of your application. If you want this object to be used as a singleton you would provide a static method to get the one and only instance of the class.
public class Foo
{
private static Foo instance ....
private Foo()
{
.....
}
public static Foo getInstance()
{
return instance;
}
}
If you plan to use a framework like spring you would just add one object to the application context.
<bean class="....Foo" id="fooInstance" scope="singleton">
....
</bean>
But maybe, you can refractor this class to hold only static methods. Then you can mark the class as final and provide a private constructor.
public final class Utils
{
private Utils(){}
public static .... doFoo(....)
{
....
}
}

Is this a valid way to ensure only a single instance of an object exists in Java?

I have been getting some strange errors with Mongodb, and in Mongodb, you are supposed to mainatin the Mongo singleton. I just wanted to make sure that this is infact valid.
public class DBManager {
public static Mongo mongoSingleton = null;
public static synchronized void getMongo(){
if(mongoSingleton == null){
mongoSingleton = new Mongo();
}
return mongoSingleton;
}
}
Thanks!
You have to set your public member mongoSingleton as private and to hide the default constructor
so
private static Mongo mongoSingleton = null;
private Mongo() {
}
the class Mongo implementation
public class Mongo {
private static volatile Mongo instance;
private Mongo() {
...
}
public static Mongo getInstance() {
if (instance == null) {
synchronized (Mongo.class) {
if (instance == null) { // yes double check
instance = new Mongo();
}
}
}
return instance;
}
}
usage
Mongo.getInstance();
This is the typical Singleton pattern, but the preferred method in Java is to create an Enum:
public enum DBManager {
INSTANCE;
// implementation here
}
You can then refer to the instance via:
DBManager.INSTANCE
Note that in either case (enum or singleton pattern), the result is one instance per ClassLoader, NOT per JVM.
public static Mongo mongoSingleton = null;
needs to be
private static Mongo mongoSingleton = null;
Other than that, looks good.
The cheapest way to do this, if you are willing to forego Lazy initialization, is to simply create the Singleton on object creation.
public final class DBManager {
private static final Mongo mongoSingleton = new Mongo();
private DBManager() {}
public static Mongo getMongo() {
return mongoSingleton;
}
}
This way, you can avoid the unnecessary synchronization overhead which would otherwise be present on every call to this method. As long as Mongo itself is thread safe, your getMongo() method is thread-safe as well.
Read the Sun developer article on Singletons here.
Just use private static final Mongo mongo = new Mongo(), or even public static final Mongo mongo = new Mongo(). It's simpler and potentially faster.
no, because public access to the static member you can change it to whatever instance you want.
More sane would be the following
public class DBManager {
private static Mongo mongoSingleton = new Mongo();
public static Mongo getMongo(){
return mongoSingleton;
}
}
Lazy initialization of singletons is overrated, usually not necessary and causes more problems than good. The naive approach to make the whole static getter synchronized is bad, because the synchronization (which is a time consuming operation) is performed every time.
There are some better approaches such as double-checked locking or the initialization-on-demand holder, but the simplest and usually the best approach is Josh Bloch's enum approach. Make an enum with a single element and you get a bullet proof singleton.
public enum Mongo {
INSTANCE;
// instance fields, methods etc. as in any other class
}
This is almost functionally equivalent to a class with a private constructor and a public static final instance, but with more concise syntax and some nice under-the-hood features that unshakeably guarantee that no other instance can be created, not even through reflection or deserialization.
It is worth noting that this approach isn't necessarily eager. The single INSTANCE is created just after the Mongo class is loaded into the JVM, which doesn't happed right after the program starts - actually it happens on the first time the class is referenced - which in this case means on the first time a static field or a method is accessed.
And if there are no other static fields other that INSTANCE and no static methods, then this really happens after the first time the INSTANCE is accessed:
Mongo mongo = Mongo.INSTANCE;
In other words, it actually is lazy without the problems of explicit synchronization.
Yes but you don't want your member variable to be public. Users have to come via your synchronised getter
If you want to see in more details, step by step- you can follow this link- http://www.javabeginner.com/learn-java/java-singleton-design-pattern
Below is one example how to do it properly.
public class DBManager {
private static Mongo mongoSingleton = null;
public static synchronized void getMongo(){
if(mongoSingleton == null){
mongoSingleton = new Mongo();
}
return mongoSingleton;
}
}

Categories