简体   繁体   English

通过公共方法初始化的私有构造函数

[英]Private Constructor initialized by a public method

I came cross a class with private constructor but the object is returned by another public method by call to the private constructor. 我遇到了带有私有构造函数的类,但是通过调用私有构造函数,该对象由另一个公共方法返回。 What may be the advantage of such a construct when we could have made the constructor public? 当我们可以将构造函数公开时,这种构造的好处是什么?

public final class TokenTable {

    static public int errorToken = 0; 
    static public int timesToken = 1;
    static public int divToken = 2;
    static public int plusToken = 11;
    ......
    ......

    private final HashMap<String, Integer> keywordMap = new HashMap();
    private final HashMap<String, Integer> operationMap = new HashMap();

    private TokenTable() {

        operationMap.put("*", timesToken);
        operationMap.put("/", divToken);
        operationMap.put("+", plusToken);
        ....



    }


    static public TokenTable getInstance() {

            LexTokenTabInstance = new TokenTable();
            return LexTokenTabInstance;
    }

}

This is called the Factory pattern. 这称为Factory模式。 Check out the description here - Factory Design Pattern . 此处查看描述-工厂设计模式

There are several advantages: 有几个优点:

  • you can have multiple named factory methods to create different flavors of the object which can allow for overloading with the same set of parameter types 您可以使用多个命名工厂方法来创建对象的不同样式,从而可以使用相同的参数类型集进行重载
  • you can return a singleton if appropriate or maybe return one of a cached set of instances 您可以根据需要返回单例,也可以返回一组缓存的实例中的一个
  • if don't need to use new 如果不需要使用new
  • when using generics, the generic type is inferred by the compiler so don't need to use the <> operator 使用泛型时,编译器会推断出泛型类型,因此无需使用<>运算符
  • you can return an interface instead of a concrete class 您可以返回接口而不是具体的类
  • allows for pre-constructor initialization (for example if init must be done prior to calling base class constructor) 允许预构造函数初始化(例如,如果必须在调用基类构造函数之前完成init)

To be clear, the above example it seems that it was done just as a "good practice" since none of the above capabilities was used (other than you don't have to use "new"). 需要明确的是,上面的示例似乎是作为“良好实践”完成的,因为没有使用任何上述功能(除了您不必使用“ new”)。

This is called a factory method. 这称为工厂方法。 A factory method has many advantages over a constructor: 与构造函数相比,工厂方法具有许多优点:

  • it has a name (and multiple factory methods may have different names) 它有一个名字(多个工厂方法可能有不同的名字)
  • it allows returning a cached instance instead of a new instance 它允许返回一个缓存实例而不是一个新实例
  • it allows returning a subclass instance instead of the actual class 它允许返回一个子类实例而不是实际的类
  • etc. 等等

The main advantage is that no one can create an instance, but using static getInstance method. 主要优点是没有人可以创建实例,但是可以使用静态getInstance方法。

This way you can make sure only one instance is created, just as Singelton design pattern 这样,您可以确保仅创建一个实例,就像Singelton设计模式一样

The primary reason for hiding a constructor of a class is to control how objects of that class are created. 隐藏类的构造函数的主要原因是控制如何创建该类的对象。 A common example of this is in the Singleton pattern, where only one object of a class is instantiated. 一个常见的例子是在Singleton模式中,其中仅实例化一个类的对象。

In order to police this, the user accesses a static method which will access the private constructor if the object isn't created, or else return a reference to the already created object: 为了解决这个问题,用户访问一个静态方法,如果未创建对象,该方法将访问私有构造函数,否则返回对已创建对象的引用:

public class SingletonDemo {
    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {       }

    public static SingletonDemo getInstance() {
            if (instance == null) {
                    synchronized (SingletonDemo.class){
                            if (instance == null) {
                                    instance = new SingletonDemo();
                            }
                  }
            }
            return instance;
    }
}  

For other examples, look at Factory patterns in general: http://en.wikipedia.org/wiki/Factory_method_pattern 对于其他示例,请查看一般的Factory模式: http : //en.wikipedia.org/wiki/Factory_method_pattern

If you do not want to protect creation of multiple instance outside the class then you can create private constructor. 如果您不想保护在类之外创建多个实例,则可以创建私有构造函数。
This is helpful creating a single instance. 这有助于创建单个实例。
You can do it like(Eager loading): 您可以像这样(急于加载):

private static final TokenTable tokenTable = new TokenTable();

static public TokenTable getInstance() {

          return tokenTable;
    }

Or, you can do it like(Lazy loading): 或者,您可以这样做(延迟加载):

private static TokenTable tokenTable;

static public TokenTable getInstance() {
         if(null == tokenTable){
         tokenTable = new TokenTable(); 
         }
          return tokenTable;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果在私有构造函数中初始化,则从静态方法访问时,保证私有静态字段为非null - Is a private static field guaranteed to be non null when accessed from a static method if initialized in the private constructor Inheritance 私有方法和公共 - Inheritance private method and public 使用getter方法在构造函数中初始化的变量 - Variable to be initialized in a constructor with getter method 将公共方法转换为私有方法 - Converting a public method into a private method 为什么只有使用 static 方法的 class 会出现错误:“Add a private constructor to hide the implicit public one.”? - Why does only the class with the static method have the error: “Add a private constructor to hide the implicit public one.”? Spring java config to invoke a public non static method of a singleton class with private constructor - Spring java config to invoke a public non static method of a singleton class with private constructor java内部类私有构造函数,public成员 - java inner class private constructor, public members Java用Package Private Constructor继承公共类 - Java Inheriting a public class with Package Private Constructor 一个类可以同时具有公共和私有构造函数吗? - Can a class have both public and private constructor? 内部私人阶级和公共方法 - Inner private class and public method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM