Java 如何在静态main中使用非静态方法(观察者方法)
想在static main中使用非静态方法,但我不能。我知道这个问题,但因为我使用INotificationObserver,所以无法将registerObserver设置为静态。所以我可以解决我的问题 我怎样才能解决这个问题??谢谢 非静态变量不能从静态上下文引用此变量 测试Java 如何在静态main中使用非静态方法(观察者方法),java,oop,design-patterns,Java,Oop,Design Patterns,想在static main中使用非静态方法,但我不能。我知道这个问题,但因为我使用INotificationObserver,所以无法将registerObserver设置为静态。所以我可以解决我的问题 我怎样才能解决这个问题??谢谢 非静态变量不能从静态上下文引用此变量 测试 public class PushTest implements INotificationObserver{ NotificationService ns = NotificationService
public class PushTest implements INotificationObserver{
NotificationService ns = NotificationService.getInstance();
public static void main(String[] args) {
try {
ns.registerObserver(this); // How can i register ???
接口
public interface INotificationSubject {
public void registerObserver(INotificationObserver o);
public void removeObserver(INotificationObserver o);
public void notifyObserver(PushedNotification notification);
}
*通知服务*
公共类NotificationService实现INotificationSubject{
受保护的静态最终记录器Logger=Logger.getLogger(NotificationService.class);
私有易失性静态通知服务唯一工厂;
私人ArrayList观察员;
私人通知服务(){
Observators=新的ArrayList();
}
公共静态NotificationService getInstance(){
if(uniqueFactory==null){
已同步(NotificationService.class){
if(uniqueFactory==null){
uniqueFactory=newnotificationservice();
}
}
}
返回唯一工厂;
}
公共静态INotification GetNotificationObject(设备类型){
INotification messageSender=null;
if(Types==Types.IOS){
messageSender=new IosNotification();
}
返回消息发送者;
}
public void registerObserver(inotificationo){
观察员:添加(o);
}
public void removeObserver(inotification观察员){
int i=
观察员:indexOf(o);
如果(i>=0){
观察员:删除(i);
}
}
public void notifyObserver(PushedNotification通知){
对于(int i=0;i
这方面的典型解决方案是在main方法中初始化类:
public class PushTest implements INotificationObserver{
NotificationService ns = NotificationService.getInstance();
public static void main(String[] args) {
PushTest pushTest = new Pushtest();
...
etc etc您需要一个实例:
INotificationObserver ino = new PushTest();
ns.registerObserver(ino);
因此,您不需要使用
ns
属性。谢谢@jlordo!但是为什么呢?你能解释一下吗,或者你能推荐一篇文章来理解吗?main
是一个static
方法,它属于类,而不是该类的实例此
指向当前实例,因此它只能在实例方法中使用。在主方法中创建实例,而不是在外部创建实例。静态方法与类关联,不能访问作为类实例的非静态变量。
INotificationObserver ino = new PushTest();
ns.registerObserver(ino);