本文介绍了继承main方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个基类,该基类定义实例化该类并运行一个方法的主要方法.虽然有两个问题.这是基类:

I want to define a base class that defines a main method that instantiates the class, and runs a method. There are a couple of problems though. Here is the base class:

public abstract class Strategy
{
    abstract void execute(SoccerRobot robot);

    public static void main(String args)
    {
        Strategy s = new /*Not sure what to put here*/();
        s.execute(new SoccerRobot())
    }
}

这是派生类的示例:

public class UselessStrategy
{
    void execute(SoccerRobot robot)
    {
        System.out.println("I'm useless")
    }
}

它定义了一个简单的execute方法,在用作主要应用程序时应在main方法中调用它.但是,为此,我需要从基类的main方法中实例化派生类.似乎不可能.

It defines a simple execute method, which should be called in a main method upon usage as a the main application. However, in order to do so, I need to instantiate the derived class from within the base class's main method. Which doesn't seem to be possible.

我宁愿不必为每个派生类重复main方法,因为这似乎有些不必要.

I'd rather not have to repeat the main method for every derived class, as it feels somewhat unnessary.

是否有正确的方法?

推荐答案

将主方法移到单独的类中.单独的关注事项
策略(名称说明一切)
启动器(将组件组装在一起并触发执行)

Move the main method out into a separate class. Separate concerns
Strategy (the name says it all)
Launcher (assembling components together and triggering execution)

public class Launcher
{
    public static void main(String args)
    {
       Strategy s = new UselessStrategy();
          //OR Strategy s = CreateInstance(args[0]) ;
          //OR equiv mechanism for Dependency Injection if you don't want to hardcode the derived strategy to use.
        s.execute(new SoccerRobot())
    }
}

这篇关于继承main方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 18:24