-1

当一个类继承这个类并覆盖这些生命周期方法时,如何创建一个具有一些按某种顺序执行的方法(即类的生命周期方法)的类?

例如:

  1. 在 Servlet 中,首先调用 init(),然后调用 service(),最后在创建 servlet 对象时自动调用 destroy()。

  2. android中的Activity有生命周期方法onCreate()、onStart()、onResume()等,当Activity对象存在时会自动调用

4

4 回答 4

1

在最简单的情况下,您可以使用模板方法方法来满足您的要求:

public class Template {
  public void templateMethod() {
    detail1();
    detail2();
  }
  protected void detail1() {}
  protected void detail2() {}

}

然后你子类化 Template 类。

于 2012-10-09T11:34:04.107 回答
1

这些方法的顺序是由引用您的类的框架/容器规定的。我通常希望您的框架需要客户端实现特定的接口(包含start()stop()),并且框架本身将确定状态机和后续行为。

于 2012-10-09T10:45:32.407 回答
1

Java的生命周期方法

由于小程序在浏览器中运行,因此 Applet 类包含生命周期方法。生命周期方法也称为环回方法。

在 java.applet.Applet 我们有四种生命周期方法。他们是

public void init (),
public void start (),
public void stop () 
public void destroy ().

1. public void init():

This is the method which is called by the browser only one time after loading the applet.
In this method we write some block of statements which will perform one time operations, such as, obtaining the resources like opening the files, obtaining the database connection, initializing the parameters, etc.

2. public void start():

  After calling the init method, the next method which is from second request to sub-sequent requests the start method only will be called i.e., short method will be called each and every time.
In this method we write the block of statement which provides business logic.

3. public void stop():

  This id the method which is called by the browser when we minimize the window. 
In this method we write the block of statements which will temporarily releases the resources which are obtained in init method.

4. public void destroy():

This is the method which will be called by the browser when we close the window button or when we terminate the applet application.
In this method we write same block of statements which will releases the resources permanently which are obtained in init method.

另一个不是生命周期方法的方法是 public void paint()。这是在启动方法完成后将被浏览器调用的方法。此方法用于在浏览器上显示数据。Paint 方法在内部调用名为 drawString 的方法,其原型如下所示。java.awt.Graphics (Graphics => public void drawString (String, int row position, int column position)) 将小程序加载到浏览器后,会自动创建一个 Graphics 类的对象。

于 2012-10-09T10:48:07.793 回答
1

您需要应用程序容器(最简单的解释是它是某个类,它将按指定顺序执行您的类的指定方法)。但是您需要更深入地了解应用程序容器的概念。我建议您阅读有关Spring的内容

于 2012-10-09T10:51:12.827 回答