我写了时间转换程序(即秒到分和分秒等),但后来我发现这些类执行类似的操作。有没有办法将这些类联系起来,如果有请给出一些解决方案和建议。这是我的代码....
二.java
import java.util.concurrent.*;
public class Second {
private long secondsValue;
public Second() {
secondsValue = 0L;
}
public Second(String from, String to, long unitValue) {
unitSelection(from, to, unitValue);
}
private void convertSecondToMinute(long unitValue) {
unitValue = TimeUnit.MINUTES.convert(unitValue, TimeUnit.SECONDS);
secondsValue = unitValue;
}
private void convertSecondToHour(long unitValue) {
unitValue = TimeUnit.HOURS.convert(unitValue, TimeUnit.SECONDS);
secondsValue = unitValue;
}
private void convertSecondToDay(long unitValue) {
unitValue = TimeUnit.DAYS.convert(unitValue, TimeUnit.SECONDS);
secondsValue = unitValue;
}
private void convertSecondToWeek(long unitValue) {
unitValue = unitValue/60/60/24/7;
secondsValue = unitValue;
}
public long getSeconds() {
return secondsValue;
}
private void unitSelection(String from, String to,
long unitValue) {
if( from.equalsIgnoreCase("second")) {
if(to.equalsIgnoreCase("minute")) {
convertSecondToMinute(unitValue);
}
else if(to.equalsIgnoreCase("hour")) {
convertSecondToHour(unitValue);
}
else if(to.equalsIgnoreCase("day")) {
convertSecondToDay(unitValue);
}
else if(to.equalsIgnoreCase("week") ) {
convertSecondToWeek(unitValue);
}
else {
System.out.println("Invalid argument...!");
}
}
}
}
分钟.java
import java.util.concurrent.TimeUnit;
public class Minute {
private long unitMinute;
public Minute() {
unitMinute = 0L;
}
public Minute(String from, String to,
long unitValue) {
unitSelection(from, to, unitValue);
}
private void convertMinuteToSecond(long unitValue) {
unitValue = TimeUnit.SECONDS.convert(unitValue, TimeUnit.MINUTES);
unitMinute = unitValue;
}
private void convertMinuteToHour(long unitValue) {
unitValue = TimeUnit.HOURS.convert(unitValue, TimeUnit.MINUTES);
unitMinute = unitValue;
}
private void convertMinuteToDay(long unitValue) {
unitValue = TimeUnit.DAYS.convert(unitValue, TimeUnit.MINUTES);
unitMinute = unitValue;
}
private void convertMinuteToWeek(long unitValue) {
long value = unitValue /60/24/7;
unitMinute = value;
}
public long getUnitMinute() {
return unitMinute;
}
private void unitSelection(String from, String to,
long unitValue) {
if( from.equalsIgnoreCase("minute")) {
if(to.equalsIgnoreCase("second")) {
convertMinuteToSecond(unitValue);
}
else if(to.equalsIgnoreCase("hour")) {
convertMinuteToHour(unitValue);
}
else if(to.equalsIgnoreCase("day")) {
convertMinuteToDay(unitValue);
}
else if(to.equalsIgnoreCase("week") ) {
convertMinuteToWeek(unitValue);
}
else {
System.out.println("Invalid argument...!");
}
}
}
}