Singleton or static methods for DAO?
Which is the preferred way of creating a DAO which has no state...Singleton or static methods for DAO? and why? What are the issues implement one over the other?
A [url http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html]DAO is an object that abstracts different data source access mechanisms by providing a common interface, decoupling the client code from the data layer implementation, and allowing differrent data sources to be used without changing the client code.
This is not possible with static methods- you would have to change the client code to use a different data source.
There is a similar pattern, the facade, where an object/utility class provides the interface to a set of functionality. In the case of a facade with static methods, the facade class needs to be rewritten to use a different implementation. This is possible, but means only one implementation may exist in each version of the software. A static method facade is a tighter coupled solution to a similar problem; tight coupling occasionally makes a measurable improvement in performance, but always reduces flexibility and requires destructive editing to change its implementation.
Pete
Similar Messages
-
No static methods for Interfaces ?
Hi,
I was going though some documentation about the interfaces and it says that, an interface methods must not be static.
Can someone please explain or direct me in the direction which tell me why the internet methods cannot be static.
Thanx.
MelDefining a static method in a interface would be useless, since static methods can't be executed with dynamic binding. You'd have to know the name of the implementing class of the interface at compile time to call it, which would negate the need for an interface.
For more details google it, that question has been asked thousands of times. -
Singleton without Static Methods
Hi all,
Is there a way to make a Singleton without using static methods?
I dont want to create new instances. I just want that single instance of a class but can find a way to access it without a static method.
Any ideas?mycoffee wrote:
gcameo wrote:
Hi all,
Is there a way to make a Singleton without using static methods?
I dont want to create new instances. I just want that single instance of a class but can find a way to access it without a static method.
Any ideas?Another way. In the class, create a static (still static) variable instanceCount
Write a close() method and call it whenever you are done with the class
then if the contructor is called, add 1 to the count. in the close() substract 1 from teh count
If the contructor is called when the count = 1 throw new Exception("I want to be alone"); LOLOuch, sounds like the worst solution so far. -
Which one of the is better?
class with all static methods
(or)
single ton class
Regards,
GovindSingleton is a design pattern used to ensure that only one instance of a class can ever exist. A static method is not a design pattern it just makes it possible to call this method on a class without ever having to have created an instance of the class. In fact it has nothing to do with the instance. there could be none or 20 instances.
-
Singleton Versus Static method
Can some body explain me advantange of making a class single ton over making all attribute and Operation static? I know Single ton means user can create only instance of the object. Can't same functionality be achieved by making all attributes and operations in class static and making constructor private to prevent them from making instance?
I know Single ton means user can create only
instance of the object.You can use more than one instance in singleton pattern if you want. But, in this case, the name "singleton" wouldn�t be appropriate.
In most of cases only one instance is used in singleton. It is more usual. But you can use more than one instance, limiting the number of active instances of your singleton. You can achieve this using an array that will contain instances of this singleton. You can set this array with an amount of elements that corresponds with the maximum amount of instances of this singleton.
I don�t know preciselly if the performance of the application is better when you define, for example, 5 instances of your singleton at the most, rather than only one instance. I just mention this because I�ve already seen something like this. Maybe it improves the performance, I don�t know.... -
Static methods, what for?
What are static methods for? is there something that is not possible through methods associated with instances (non-static methods) ?
There are many examples of static mehods in the Java API. For example the Math or the System class. All methods in this classes are static. So you dont have to instantiate the system class. In fact it is even not possible to instantiate the System class. System is final and all Constructors are private.
Another use for static methods is the access to private static variables. -
Singleton vs static - which is better?
Of the two approaches -
a class which can be used by accessing its ONLY instance(singleton) or a class which has a set of static methods which can be invoked on the class itself
which is better and why? Or are these just two 'styles' of programming?
I always get confused as to which way to go? I tend to prefer to have static methods on the class instead of a singleton.
All insights/comments/ideas welcome.
ThanksWell, there are a few questions you can ask - does the method cause any changes of state, or is it a pure function? If the latter, static is probably the way to go.
The way you are talking, I gather that there is some state involved.
Next question: does it make sense for there to be more than one of these per JVM? Not only in the way you currently envision it, but at all, anywhere. For example, consider the list of Strings that the String class keeps so it can consolidate memory and avoid duplication (see String.intern() ). That list makes sense to be static.
On the other hand, the representation of the state of a board game should not be static, because someone could want to write a program which has multiple games within it - or you could within one game wish to have contingencies or undo-ability (essentially, it might not be as singleton as you think).
Next, if you think the methods will ever need to be overridden, use a singleton, because static methods aren't, well, dynamic! (in case the singleton is a one-at-a-time singleton but it makes sense to have a change of identity over time).
I have never written a true singleton - though often written classes which I did not PLAN on instantiating more than once. -
Why not to use static methods - with example
Hi Everyone,
I'd like to continue the below thread about "why not to use static methods"
Why not to use static methods
with a concrete example.
In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
I created the following class for these "operations" with static methods:
public class KeyboardInput {
private static Robot r;
static {
try {
r = new Robot();
} catch (AWTException e) {
throw new RuntimeException(e + "Robot couldn't be initialized.");
public static void wait(int millis){
r.delay(millis);
public static void copy() {
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_C);
r.keyRelease(KeyEvent.VK_CONTROL);
public static void altTab() {
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_ALT);
// more methods like paste(), tab(), shiftTab(), rightArrow()
}Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
Thanks for any comments in advance,
lemonbostonmaheshguruswamy wrote:
lemonboston wrote:
maheshguruswamy wrote:
I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
If you use a Singleton (and and interface), you can do something like this:
KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class. -
From Classic abap FMs to ObjectOriented instance/static methods: reference
Hi All,
we are migrating one of our project developed using classic abap to abap objects.
mostly we are replacing the Function modules with either instance methods or static methods.
for e.g.
if there are FMs like GUI_UPLOAD, SO_NEW_DOCUMENT_SEND_API1 are used, after exploring in sdn for abap objects, we realized
we can use cl_gui_frontend_services=>gui_upload( ) instead of the GUI_UPLOAD.
send_request = cl_bcs=>create_persistent( ). send_request->send( ). can be used instead of SO_NEW_DOCUMENT_SEND_API1
like that there are several FMs present, is there any easy way where we can find this reference of object oriented methods corresponding to the plain old Function modules of classic abap.
i was thinking, after seeing the blogs of people like Thomas Jung, Horst Keller, they encouraged a lot on abap objects over procedural abap. are there any such guidlines, references present to migrate (rather upgrade) to abap objects from existing procedural abap
thanks,
Madhu_1980I don't think it makes sense to do 1:1 mapping and replacement in your code.
It does make sense to refactor using Object oriented techniques and patterns but it is usually a non-trivial task. -
How to create a method for reading a file
i tried to make it as static method for reading a file and
then to return string
is this code correct?
public static String fileMaterial(String fileName)
fileReader = new BufferedReader(new FileReader(fileName));
info = fileReader.readLine();
while(school != null) {
return info;
info = fileReader.readLine();I created a class you might want to look at. I come from a world of C and love fgets() and other FILE stream functions. I created a class that uses the Java I/O buts to the calling application behaves like fgets and such. The block of code where I do the calling in the calling program even looks like C. In my class I capture almost all errors and set error buffers to the errors. The calling program looks at the return to see if it succedded or errored.
BuffIO new = BuffIO.fopen("fiilename", "r");
String s;
if((s = new.fgets()) == null)
System.err.println("error reading file: " + new.ferror());
That would be waht the calling program does -
I'm writting a wrapper for exception handling.One of the classes uses log4j to log exceptions.I want to write a interface to generalize loggin.Idealy I should have an interface with certain static methods for loging (i.e logError,logDebugMessage,consoleError,consoleMessage,etc) , but Interface dosent allow that and neither do abstract classes can havstatic method declarations.The implementations of these methods will achieve the hiding of the complexity of using a logging package,log levels etc from the user.
Let me know how best I can work something out for this.
Thanks in advanceDefine them once (as final) in an abstract class. Then any subclass can call logError etc.
Kind regards,
Levi -
I have a static method in my class .
Now i want to change my class to Distributed class
So what to do with that static method ...
I can't take in interface , so how i can call that method
Sunil VirmaniThe pre condition of all the remote methods is that they should have been declared in the interface implementing RemoteInterface. Now its been discussed in detail in this forum already why we cannot have static methods declared in the interface therefore by nature not being polymorphic u cannot use static methods for the aforesaid purpose.
-
Why is the static method in the superclass more specific?
Why is the static method in the superclass more specific than the static method in the subclass? After all, int is a subtype of long, but Base is not a subtype of Sub.
class Base {
static void m(int i){ System.out.println("Base"); }
class Sub extends Base {
static void m(long l){ System.out.println("Sub"); }
class Test {
public static void main(String[] args) {
int i = 10;
Sub sub = new Sub();
sub.m(i);
}The first example compiles without error.
Output: Base
class Base {
void m(int i){ System.out.println("Base"); }
class Sub extends Base {
void m(long l){ System.out.println("Sub"); }
class Test {
public static void main(String[] args) {
int i = 10;
Sub sub = new Sub();
sub.m(i);
}In the second example, both instance methods are applicable and accessible (JLS 15.12.2.1), but neither is more specific (JLS 12.2.2), so we get a compiler error as expected.
: reference to m is ambiguous,
both method m(int) in Base and method m(long) in Sub match
sub.m(i);
^
1 error
Why don�t we get a compiler error for the static methods?Thank you for your ideas.
====
OUNOS:
I don't get Sylvia's response. This is about static methods, what are instances are needed for??Yes, the question is about static methods. I included the example with non-static methods for a comparison. According to JLS 15.12.2, both examples should cause a compiler error.
And why you create a Sub object to call the method, and dont just call "Sub.m(..)"Yes, it would make more sense to call Sub.m(i). Let�s change it. Now, I ask the same question. Why is there no compiler error?
====
DANPERKINS:
The error in your logic stems from calling static methods on instances, as ounos pointed out. Solution: don't. You won't see any more ambiguities.A static member of a class may also be accessed via a reference to an object of that class. It is not an error. (The value of the reference can even be null.)
Originally I was looking only at the case with non-static methods. Therefore, I used sub.m(i). Once I understood that case, I added the static modifiers. When posting my question, I wish I had also changed sub.m to Sub.m. Either way, according to JLS 15.12.2, a compiler error should occur due to ambiguous method invocation.
====
SILVIAE:
The question was not about finding an alternative approach that doesn't throw up an ambiguity. The question related to why, in the particular situations described, the ambiguity arises in only one of them.
Yes.
Proposing an alternative approach doesn't address the question.
Yes.
====
If anyone is really interested, here is some background to the question. Some people studying for a Sun Java certificate were investigating some subtleties of method invocations:
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=019182
I remember seeing the non-static case discussed in this forum once before in a more practical context. jschell probably knows the link. -
Why is it necessary to create an instance via the static method?
Hi,
For some classes (such as java.util.regex.Pattern), we should call the class method (static method) in order to create an instance (object).
For example, in order to conduct the pattern matching, we should use the java.util.regex.Pattern class as follows:
Pattern p = Pattern.compile ("X[0-9]+X") ;
// An instance of the Pattern class is created.
Matcher m = p.matcher ("abcX1XYX23Xz") ;
while ( m.find() ){
System.out.println ( m.start() ) ;
}where the compile static method in the Pattern class creates an instance and returns the pointer (reference) of it. We should NOT call
the constructor of the Pattern class as follows:
Pattern p = new Pattern ("X[0-9]+X") ; // ERRORThe question is the following:
(1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?
(2) Why do the java.util.regex.Pattern class have such a specification?
Thanks in advance.(1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?1. As the other author mentioned, caching is one reason.
2. With such caching, you don't need to take trouble in passing the reference of a cached object(s) to many places in your code. From anywhere in your code base, you can simply invoke the method, the object will come. In essence, the static method provides a global point of access to one or more pre-created (or cached) objects. Hence, the static method simplifies access to the object.
3. Sometimes, the actual class instantiated is not the same as the one with the static method. This allows abstraction of underlying variations. For example, when you say Pattern.compile ("X[0-9]+X") , the returned object type can be different in Windows and Linux (Most probably Pattern class doesn't work like that, but I am showing you a use case. May be Runtime.getRuntime() does actually work like that.). You find this abstraction of variations in many places. Take for example, FacesContext.getExternalContext() method (this is from JSF API). ExternalContext documentation says this:
"This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment."
Edited by: Kamal Wickramanayake on Oct 24, 2012 8:04 AM -
Help to solve the static method....pls.
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class Main {
public Main() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
String[] subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class create_table {
public create_table() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
substring(subStr); //problem at here
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// problem at here
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
static void substring(String[] subStr)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
String text;
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
*on top is the original code, bottom is after modified
i would like to create a static method for the static void substring(String[] subStr). But when i use the substring() on the main program, the compiler give me error. Is that my substring () created wrongly?? pls help...package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class Main {
public Main() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
String[] subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr = text.substring(index); // extract to the end
else // otherwise
subStr = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class create_table {
public create_table() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
String[] subStr;
String[] substring;
int i;
substring(subStr); //PROBLEM: substring in readtext can not apply
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
static void substring(String[] subStr)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
String text;
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
the problem is here
String text;
while ((text = in.readLine()) != null)
String[] subStr;
String[] substring;
int i;
substring(subStr); //PROBLEM: substring in readtext can not apply
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
the system say that my substring(subStr[i]) (java.lang.String[])in read.text can not applied to (java.lang.String)...how can i solve for tis problem? is that i have to use for loop to create an array for subStr???
Maybe you are looking for
-
How can I create multiple accounts without the necessity to create multiple email addresses? I now have 2 i-phones (mine and my wife's), 1 i-pad (mine), 1 i-pad mini (10 year old's), and 1 I-pod touch (11 year old's). I would like to maintain purch
-
Quit the Apex engine using wwv_flow.g_unrecoverable_error
Hi all I have used wwv_flow.g_unrecoverable_error := TRUE to quit the apex engine (mainly in my exception handlers) and then issue a owa_util.redirect_url api call. Under some circumstances, I have needed to reinitiate using htp.init; I have not been
-
Exceptions thrown after installing Forte4j and j2ee toolkit
Hi! I've got a problem with Forte4j. I installed Forte4j and i worked fine. Then I insatlled the j2ee toolkit and Forte started to throw exceptions at startup. The added functionality I expected from the j2ee toolkit doesn't appear to be there either
-
How to differentiate PO's in different colors in abap editor
Dear sir, I had created five Purchse request using ME51N Transaction. I would like to write each PO in each color using ABAP editor. With Regards, Baskaran
-
Syncing 2 Calendars in iPhone 3G
Currently I have a work calendar and a personal calendar both on Outlook 2007. I want to be able to sync both onto the phone w/o having the respective calendar going onto the computer. I would also like to know how to make each one a separate calenda