避免在java中实例化一个类 [英] Avoid instantiating a class in java

查看:144
本文介绍了避免在java中实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了一个问题:如何避免实例化一个Java类

Recently I've faced a question : How to avoid instantiating a Java class?

但是,我回答说: p>

However, I answered by saying:


  1. 如果您不想实例化类,请使用abstract修饰符。例如:javax.servlet.HttpServlet被声明为abstract(尽管它的方法都不是抽象的),以避免实例化。

  1. If you don't want to instantiate a class, use "abstract" modifier. Ex: javax.servlet.HttpServlet, is declared as abstract(though none of its methods are abstract) to avoid instantiation.

声明一个无参数私有构造函数。

Declare a no argument private constructor.

现在我的问题是
a)有没有其他方法?
b)为什么有人不想实例化一个类? - 在搜索SO后,我从 this 了解到Util类可以不要实例化。

Now my question is a) are there any other ways? b) why does any one do not want to instantiate a class? - after searching in SO, I got to know from this that Util classes can be made not to instantiate. Any other places where we don't want to instantiate a class in OOP?

推荐答案

有四个原因让人想起:


  1. 允许子类但不允许实例化父类;

  2. 禁止直接实例化,而是提供返回工厂方法并在必要时创建实例;

  3. 因为所有实例都是预定义的(例如套牌中的套装),但是从Java 5开始,类型安全枚举推荐替代;和

  4. 类确实不是类。

  1. To allow subclasses but not the parent to be instantiated;
  2. To disallow direct instantiation and instead provide a factory method to return and if necessary create instances;
  3. Because all the instances are predefined (eg suits in a deck of cards) although since Java 5, typesafe enums are recommended instead; and
  4. The class really isn't a class. It's just a holder for static constants and/or methods.

作为(2)的示例,您可能需要创建规范对象。例如,RGB颜色组合。您不想创建多个任何RGB组合的实例,因此您可以这样做:

As an example of (2), you may want to create canonical objects. For example, RGB color combinations. You don't want to create more than one instance of any RGB combo so you do this:

public class MyColor {
  private final int red, green, blue;

  private MyColor(int red, int green, int blue) {
    this.red = red;
    this.green = green;
    this.blue = blue;
  }

  public static MyColor getInstance(int red, int green, int blue) {
    // if combo already exists, return it, otherwise create new instance
  }
}

注意:no no-arg constructor is因为另一个构造函数是显式定义的。

Note: no no-arg constructor is required because another constructor is explicitly defined.

这篇关于避免在java中实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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