作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在尝试继承一个后跟单例模式的类时遇到了问题。假设有一个名为 P 的类,其后是单例模式并实现了一个名为 I_able 的接口(interface)。
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
现在,有两个类想从 P 继承如下。
class A inheritance P {
static public I_able getInstance() {
if ( instance == null )
instance = new A() ;
return (A) instance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // A()
class B inheritance P {
static public I_able getInstance() {
if ( instance == null )
instance = new B() ;
return (B) instance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // B()
问题是为什么A中的实例和B中的实例是同一个对象。实际上,我有点知道为什么会这样,但我想知道如何解决这个问题。A 和 B 必须是程序中唯一的对象。有什么建议吗?
最佳答案
您的代码中的问题是您的static I_able 实例
是在您的父类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()
关于java - 从单例模式继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46270931/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!