现在让我们来看一个经常被忽略的重构,提取接口。但我们注意到超过一个的类要使用某一个类中方法的子集时,我们应该切断它们之间的依赖,让消费者(consumers)使用接口,这非常容易实现但却降低了代码的耦合性。
1: public class ClassRegistration
2: {
3: public void Create()
4: {
5: // create registration code
6: }
7:
8: public void Transfer()
9: {
10: // class transfer code
11: }
12:
13: public decimal Total { get; private set; }
14: }
15:
16: public class RegistrationProcessor
17: {
18: public decimal ProcessRegistration(ClassRegistration registration)
19: {
20: registration.Create();
21: return registration.Total;
22: }
23: }
我们来对上面的代码进行重构,我们将ClassRegistration类中的Total属性、Create方法提取到接口中,这样ClassRegistration类的消费者就不用关心ClassRegistration的具体实现,
从而降低了代码的耦合性。下面是重构后的代码:
1: public interface IClassRegistration
2: {
3: void Create();
4: decimal Total { get; }
5: }
6:
7: public class ClassRegistration : IClassRegistration
8: {
9: public void Create()
10: {
11: // create registration code
12: }
13:
14: public void Transfer()
15: {
16: // class transfer code
17: }
18:
19: public decimal Total { get; private set; }
20: }
21:
22: public class RegistrationProcessor
23: {
24: public decimal ProcessRegistration(IClassRegistration registration)
25: {
26: registration.Create();
27: return registration.Total;
28: }
29: }
这个重构最早由Martin Fowler发表,你可以这里查看。
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/07/refactoring-day-9-extract-interface.aspx
This refactoring was first published by Martin Fowler and can be found in his list of refactorings here.