简体   繁体   中英

The best way to reuse objects

I've been looking through some of my classes and it seems that every time I need a new input I make a new scanner (if the class doesn't have a scanner). Is there some way to reuse scanners, or any other object between multiple classes?

Premature optimization is a bad thing (tm). As are singletons.

Too often the performance issues you worry about are not the ones that your program bogs down in. So just create the scanners and enjoy the readable code.

If you run into performance issues, analyze the code. If it turns out that scanners are the performance bottleneck cause all your application does is create and discard scanners, then is the time to start thinking about reusing them at that particular part of the code.

Or more likely, replacing them with a bit more low-level objects, like BufferedReader and Pattern and Matcher.

也许将其放入实用程序类或类似的单例。

The singleton pattern is one way to do this. Another is to implement something like Java string internalization. You can maintain a static set of existing scanners and only create a new scanner if it is not already in the set.

Creating multiple scanners does not need to be a problem unless you want them to access the same file. One option is to make a util class that either contains a static scanner or using a singleton.

A singleton is made like this :

class Singleton 
Singleton singleton 
private Singleton(){
//constructon
}

public synchronised singleton getsingleton(){
   if (singleton==null)
       singleton=new Singleton()
 return singleton 
}

your other option is to make it like this

class utils {
     public static scanner scan
}

which can be accessed using

utils.scan 

instead of your normal variable name.

Do however keep in mind that 2 scanners behave differend then 1 scanner. For example let's say we have a file scanner that is midway trough a file now another object reads the next word, if you split over 2 scanners then the origenal will read the same word but if you have one scanner it will not. For example 2 scanners A and B both read created for the text "this is an example"

print(A.next())
print(B.next())
print(A.next())
print(B.next())
would give us "this this is is" 
if however we run it with just a single scanner we get 
print(A.next())
print(A.next())
print(A.next())
print(A.next())
which would give us "this is an example" 

So remember that a single scanner will not behave the same as 2 scanners, this is especially notable if you try and do something like multitreading. So if it's just to try and save those variable names you might not want to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM