问题描述
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这样子会影响内存和系统性能,如何优化这段代码呢? 问题补充:blessed24 写道
解决方案
单例模式: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()); } }}
解决方案二:
改成单例模式还不行吗?
解决方案三:
WsRequest写成单例模式的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(); } }
解决方案四:
客户端调用 WsRequest wr = WsRequest.getInstance();
解决方案五:
WsRequest类能修改么?我大致写一下private static WsRequest wr = new WsRequest();public static WsRequest getInstance(){ return wr;}
解决方案六:
WsRequest 是自己编写的吧,你可以写一个方法让客户端每次取的都是同一个对象
解决方案七:
运用单例,每次使用同一个对象,是这个意思吧