如何解决抽象静态方法设计问题? [英] How to resolve abstract static method design issue?

查看:56
本文介绍了如何解决抽象静态方法设计问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个队列都扩展了 Queue 类。我想做一个队列管理器基类来处理添加到队列中(和其他操作)。

I have several queues that all extend a Queue class. I want to do a Queue manger base class to handle adding to the queue (and other operations).

如果您看下面的代码,我创建了一个名为 QueueManger 的基类,该基类具有静态方法名为 add()的将获得队列并向其中添加变量。我想将 getQueue()(在add()中调用)抽象化,因为我想强制其他类提供自己的 Queue实现。问题是我无法声明抽象静态方法。解决这个问题的正确方法是什么?

If you take a look at the following code, I created a base class called QueueManger that has a static method called add() that will get 'Queue' and add a variable to it. I want to make getQueue() (called in add() ) abstract because I want to force other classes to provide their own implementation of the 'Queue'. The issue is I can't declare abstract static method. What is the right way to solve this?

public class RegistrationQueueManger {
    @Override
    Queue getQueue() {
        return new RegistrationQueue(); // RegistrationQueue is a class that
                                        // extends Queue.java
    }
}

public abstract class QueueManger {
    abstract static Queue getQueue(); // Error: cant do! (in java)

    public static Add(String myvar) {
        getQueue().add(myvar);
    }
}

注意:我看到了一些关于此的问题主题,但对于如何解决它并创建另一个设计来处理它并没有给出很好的答案。

推荐答案

仅实例方法可以被覆盖。因此,对静态方法进行抽象是没有意义的。 getQueue 方法也不应该是静态的, add 方法也不应该是静态的。

Only instance methods may be overridden. So abstract on a static method doesn't make sense. The getQueue method shouldn't be static, and the add method shouldn't be static either.

这篇关于如何解决抽象静态方法设计问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆