简体   繁体   中英

Overload or Override int method() for toString() formatted output?

I have a class that stores a number in the millions. What I would like to do is override the method to get that number and apply a string formatter for readable UIX output.

This is what I have to "overload" the to gets:

class dudViewModel {
    public int gettotal () {
        return this.total;
    }
    public String gettotal(String formated) {
        return String.format("%.1f", (float)total / 1000000);
    }   
}

So it's the difference between the two following calls:

gettotal(); // returns 23,400,000

and

gettotal("formatted");  // returns 23.4

Is there a better way or pattern in java to overload an individual method() that returns a number and override i with a tostring() call somehow to overide default number return and instead return a formatted string?

I think the best way is to separate the presentation from the business logic. In this approach, you'd just have a single getTotal() method returning int . A completely separate method of a separate class would take that int and format it for the UI.

or patter in java to overload an individual method() that returns a number and override i with a tostring()

您可以应用Decorator模式 ,该模式允许将行为静态或动态地添加到单个对象,而不会影响同一类中其他对象的行为

Separate the data from its representation and you can also test it in isolation.

class Dud {

   public int getTotal () {return this.total;}
}

class DudPresentation {

     private Dud dud;         

     public DudPresentation(Dud dud){
         this.dud = dud;
     }


     public String getTotal() {
         return getTotal("%.1f");
     }

     public String getTotal(String format) {
         int total = dud.getTotal();
         return String.format(format, (float)total / 1000000);
     }   

}

What a method does, must be indicated in its name. In this case, the two methods should be named different rather than trying to overload, overloading should alter the processing, not the total effect or output.

class dud {
   public int getTotal () {return this.total;}
   public String getFormattedTotal() {return String.format("%.1f", (float)total / 1000000);} 
   public String getFormattedTotal(String customFormat) {return String.format(customFormat, (float)total / 1000000);}  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM