public void run() {
try {
WsRequest req=new WsRequest(xmlText);
System.err.println(req.getCode());
System.err.println(req.getNodes("MoSms"));
} catch (Exception e) {
e.printStackTrace();
}
}
上面这段代码是每隔30秒就执行一次的。也就是说WsRequest对象一直被new这样子会影响内存和系统性能,如何优化这段代码呢?
单例模式:
[code="java"]public class Singleton{
private Singleton(){
generator = new Random();
}
public void setSeed(int seed){
generator.setSeed(seed);
}
public int nextInt(){
return generator.nextInt();
}
public static synchronized Singleton getInstance(){
if (instance == null) {
instance = new Singleton();
}
return instance;
}
private Random generator;
private static Singleton instance;
}
客户端调用的代码:
package singleton;
public class Client{
public static void main(String[] args){
Singleton s1 = Singleton.getInstance();
System.out.println(s1.toString());
for(int i=0;i<10;i++){
Singleton s2 = Singleton.getInstance();
System.out.println("The randomed number is "+s2.toString());
}
}
}[/code]
运用单例,每次使用同一个对象,是这个意思吧
WsRequest 是自己编写的吧,你可以写一个方法让客户端每次取的都是同一个对象
WsRequest类能修改么?
我大致写一下
private static WsRequest wr = new WsRequest();
public static WsRequest getInstance(){
return wr;
}
客户端调用
WsRequest wr = WsRequest.getInstance();
WsRequest写成单例模式的
[code="java"]public class WsRequest
{
private static WsRequest wsRequest = new WsRequest();
private String xmlText;
private WsRequest(String xmlText)
{
this.xmlText = xmlText;
//TODO
}
public static synchronized WsRequest getInstance(String xmlText)
{
if (wsRequest != null)
{
wsRequest.setXmlText(xmlText);
return this.wsRequest;
}
this.wsRequest = new WsRequest();
return this.wsRequest;
}
public void setXmlText(String xmlText)
{
this.xmlText = xmlText;
}
}
public void run() {
try {
WsRequest req=WsRequest.getInstance();
System.err.println(req.getCode());
System.err.println(req.getNodes("MoSms"));
} catch (Exception e) {
e.printStackTrace();
}
} [/code]
改成单例模式还不行吗? :o