首页 文章

创建没有构造函数的NumberFormat

提问于
浏览
2

我有以下课程:

import java.text.NumberFormat;

public static class NF
{
    public static NumberFormat formatShares = NumberFormat.getInstance();
    public static NumberFormat formatCash = NumberFormat.getInstance();

    public NF(){
        formatShares.setGroupingUsed(true);
        formatShares.setMaximumFractionDigits(0);
        formatCash.setGroupingUsed(true);
        formatCash.setMaximumFractionDigits(2);
        formatCash.setMinimumFractionDigits(2);
   }       
}

反正有没有这样做,所以我没有实例化课程?基本上我希望能够使用NF.formatCash.format(1234567.456)

3 回答

  • 0

    实际上这是不可能的 . 直接或间接创建至少一个 NumberFormat 实例 . 您可以减少这些实例的数量 .

    使用 static 对象:

    public static final NumberFormat formatShares = NumberFormat.getInstance();
    
    static {
        formatShares.setGroupingUsed(true);
        formatShares.setMaximumFractionDigits(0);
    }
    

    这对多个线程不正确,因为 NumberFormat 不是线程保存的 .

    使用 ThreadLocal 在每个线程的实例上使用:

    public static final ThreadLocal<NumberFormat> threadLocalFormatShares = ThreadLocal.withInitial(() -> {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(true);
        nf.setMaximumFractionDigits(0);
        return nf;
    });
    
    NumberFormat formatShares = threadLocalFormatShares.get();
    

    我认为这可以解决你的问题 .

  • 0

    您可以在静态初始化块中修改 NumberFormat 对象:

    public static class NF {
        public static NumberFormat formatShares = NumberFormat.getInstance();
        public static NumberFormat formatCash = NumberFormat.getInstance();
    
        static {
            formatShares.setGroupingUsed(true);
            formatShares.setMaximumFractionDigits(0);
            formatCash.setGroupingUsed(true);
            formatCash.setMaximumFractionDigits(2);
            formatCash.setMinimumFractionDigits(2);
       }       
    }
    

    初始化类时初始化块中的代码将运行,因此不需要为您的代码创建 NF 实例 .

  • 3

    你可以将你的 class 变成一个单身人士 .

    当你想使用 NF 时,它会自动完成's not entirely the format you want but it does meet your requirements in that you do not have to instantiate the class yourself, it' .

    NF.getInstance().formatCash.format(1234567.456)
    

    那么你的课就像这样:

    public class NF {
        public NumberFormat formatShares = NumberFormat.getInstance();
        public NumberFormat formatCash = NumberFormat.getInstance();
    
        private static NF theInstance;
    
        private NF() {
            formatShares.setGroupingUsed(true);
            formatShares.setMaximumFractionDigits(0);
            formatCash.setGroupingUsed(true);
            formatCash.setMaximumFractionDigits(2);
            formatCash.setMinimumFractionDigits(2);
        }
    
        public static NF getInstance() {
            if (theInstance == null) {
                theInstance = new NF();
            }
            return theInstance;
        }
    }
    

相关问题