gpt4 book ai didi

java - 从单例模式继承

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:26 24 4
gpt4 key购买 nike

我在尝试继承一个后跟单例模式的类时遇到了问题。假设有一个名为 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 中定义的。

因此,当您在类 ABgetInstance时,它们都将引用其父类的类 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com