把一個類的多個職責進行拆分,這貫徹了SOLID中的單一職責原則(SRP)。儘管對於如何劃分「職責」常常存在爭論,但應用這項重構仍是十分簡單的。我這裏並不會回答劃分職責的問題,只是演示一個結構清晰的示例,將類劃分爲多個負責具體職責的類。ide
public class Video {
public void PayFee(Double fee) {
}
public void RentVideo(Video video, Customer customer) {
customer.Videos.add(video);
}
public Double CalculateBalance(Customer customer) {
return customer.sum(customer.LateFees);
}
}
public class Customer {
public List<Double> LateFees;
public List<Video> Videos;
double sum(List<Double> LateFees){
double sum=0d;
for (Double d:LateFees){
sum=+d;
}
return sum;
}
}
public class Video {
public void RentVideo(Video video, Customer customer) {
customer.Videos.add(video);
}
}
public class Customer {
public List<Double> LateFees;
public List<Video> Videos;
public void PayFee(Double fee){}
public Double CalculateBalance(Customer customer) {
return sum(customer.LateFees);
}
double sum(List<Double> LateFees) {
double sum = 0d;
for (Double d : LateFees) {
sum = +d;
}
return sum;
}
}