Java 从单例模式继承
我在尝试继承一个后跟单例模式的类时遇到了一个问题。 假设有一个名为P的类,后跟Singleton模式,并实现一个名为I_-able的接口Java 从单例模式继承,java,oop,Java,Oop,我在尝试继承一个后跟单例模式的类时遇到了一个问题。 假设有一个名为P的类,后跟Singleton模式,并实现一个名为I_-able的接口 abstract class P implement I_able { static protected I_able instance = null; protected object member1; // abstract static I_able getInstance(); <-- this is an illeg
abstract class P implement I_able {
static protected I_able instance = null;
protected object member1;
// abstract static I_able getInstance(); <-- this is an illegal declaration.
abstract public void method1() ;
} // class P
问题是为什么A中的实例和B中的实例是同一个对象。
事实上,我有点知道这是为什么,但我想知道我如何才能解决这个问题。
A和B必须是程序中唯一的对象。
有什么建议吗?代码中的问题是您的
静态可访问实例是在父类p中定义的
因此,当您在类A
和B
中getInstance
时,它们都会引用其父类p
的静态变量instance
我不知道您到底希望函数如何执行,但这里有一个建议的编辑是在每个子类中实现Singleton
模式
class A inheritance P {
static protected I_able AInstance = null;
static public I_able getInstance() {
if ( AInstance == null )
AInstance = new A() ;
return (A) AInstance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // A()
class B inheritance P {
static protected I_able BInstance = null;
static public I_able getInstance() {
if ( BInstance == null )
BInstance = new B() ;
return (B) BInstance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // B()
也许这篇文章会帮助你理解这种行为。
class A inheritance P {
static protected I_able AInstance = null;
static public I_able getInstance() {
if ( AInstance == null )
AInstance = new A() ;
return (A) AInstance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // A()
class B inheritance P {
static protected I_able BInstance = null;
static public I_able getInstance() {
if ( BInstance == null )
BInstance = new B() ;
return (B) BInstance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // B()