在我的Java程序Chrome extension's host(或本機應用程序)中,每當主機由我的Chrome擴展程序調用時,就會創建一個類的新實例。如何防止每次調用主機時創建類的新實例?
如何防止發生?我的意思是我需要爲所有主機 - 分機 - 主機呼叫設置一個Applet對象,如何實現?
這裏是我的程序:
import javax.swing.JOptionPane;
public class Applet {
static Applet myApplet;
public Applet(){
System.err.println("new instance created!");
}
public static void main(String[] args) {
try {
if (myApplet == null)
myApplet = new Applet();
myApplet.readMessage();
myApplet.sendMessage("{\"data\": \"somee data\"}");
} catch (Exception ex) {
System.err.println("error");
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
public String readMessage() {
String msg = "";
try {
int c, t = 0;
for (int i = 0; i <= 3; i++) {
t += Math.pow(256.0f, i) * System.in.read();
}
for (int i = 0; i < t; i++) {
c = System.in.read();
msg += (char) c;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "error in reading message from JS");
}
return msg;
}
public void sendMessage(String msgdata) {
try {
int dataLength = msgdata.length();
System.out.write((byte) (dataLength & 0xFF));
System.out.write((byte) ((dataLength >> 8) & 0xFF));
System.out.write((byte) ((dataLength >> 16) & 0xFF));
System.out.write((byte) ((dataLength >> 24) & 0xFF));
// Writing the message itself
System.out.write(msgdata.getBytes());
System.out.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "error in sending message to JS");
}
}
}
我beleive沒有必要添加任何擴展或background.js代碼,但請讓我知道如果你需要看的,太。
非常感謝。
嘗試使用[單例模式](https://en.wikipedia.org/wiki/Singleton_pattern)? – Gosu