【发布时间】:2015-12-02 20:04:26
【问题描述】:
我有两个扩展抽象模型的类。这两个类都实现了一个名为 instance() 的方法,以基本上确保在任何时候都只有一个类的实例。两个类的 instance() 结构完全相同,所以我认为将它提升到抽象类会很好。但是,该方法调用实例化类的默认构造函数。是否可以从抽象类调用此构造函数?如果有怎么办?还有哪些其他方法可以推广这种方法?
简化示例类
我有一个模型的抽象类,看起来像
public abstract class Models{
public List<Model> models = new ArrayList<Model>();
/** load the different models, with the models with pre-trained model*/
public abstract void load();
}
还有两个像这样的实例化类
public class PageLanguageModels extends Models {
/** ensure we only call one of them */
protected static PageLanguageModels _instance = null;
static Logger logger = Logger.getLogger(ProductLanguageModels.class.getName());
public static synchronized PageLanguageModels instance() {
if (_instance == null) {
try {
_instance = new PageLanguageModels();
_instance.load();
} catch (Exception e) {
logger.log(Level.SEVERE, "Couldn't load language models.", e);
}
}
return _instance;
}
/** load the different models, with the models with pre-trained model*/
@Override
public void load() {
models.clear();
models.add(new BOWModel());
}
}
public class ProductLanguageModels extends Models {
/** ensure we only call one of them */
protected static ProductLanguageModels _instance = null;
static Logger logger = Logger.getLogger(ProductLanguageModels.class.getName());
public static synchronized ProductLanguageModels instance() {
if (_instance == null) {
try {
_instance = new ProductLanguageModels();
_instance.load();
} catch (Exception e) {
logger.log(Level.SEVERE, "Couldn't load language models.", e);
}
}
return _instance;
}
/** load the different models, with the models with pre-trained model*/
@Override
public void load() {
models.clear();
models.add(new Word2VecModel());
}
}
尝试的方法
我尝试过使用工厂方法模式,但这不起作用,因为实例是静态方法,并且无法从静态方法调用抽象工厂方法。
无法对非静态方法 makeModels() 进行静态引用 来自模型类型
public abstract class Models{
/** load the different models, with the models with pre-trained model*/
public abstract void load();
//Factory method
public abstract Models makeModels();
// Instance code moved up from instanciating classes
protected static Models _instance = null;
static Logger logger = Logger.getLogger(Models.class.getName());
public static synchronized Models instance() {
if (_instance == null) {
try {
_instance = makeModels();
_instance.load();
} catch (Exception e) {
logger.log(Level.SEVERE, "Couldn't load language models.", e);
}
}
return _instance;
}
}
【问题讨论】:
-
不能在抽象类中创建静态方法。在您的情况下使用 Factory 或 Builder 类可能会有所帮助。附带说明一下,要创建不同步的单例,您可以使用 Holder 模式。
标签: java constructor abstract-class