把一个类的多个职责进行拆分,这贯彻了SOLID中的单一职责原则(SRP)。尽管对于如何划分“职责”经常存在争论,但应用这项重构还是十分简单的。我这里并不会回答划分职责的问题,只是演示一个结构清晰的示例,将类划分为多个负责具体职责的类。
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;}}
如你所见,Video类包含两个职责,一个负责处理录像租赁,另一个负责管理管理用户的租赁总数。要分离
职责,我们可以将用户的逻辑转移到用户类中。
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;}}
时间: 2024-10-27 13:08:00