提取接口:当有多余一个类使用另外一个类中的方法时,可以考虑引入接口,解除这种依赖。
举例理解:比如说类A中有个方法为Call(Type T),类B和类C中都有方法都要调用Call这个方法,那么我们推荐引入一个接口,这样传参时可以直接new一个接口,可以解除调用方法和实现方法之间的耦合关系。面向接口编程也算是OO中比较重要的吧。
项目实例:一般而言在设计的时候,对于比较可能扩展的部分都会用接口或者是抽象方法来处理,对于接口,个人并不是很喜欢,因为接口写好了要修改就很困难,只能再加新的接口,这对设计的要求很高,抽象方法相对好用点。下面的代码扩展于原文的Demo Code,希望可以讲得稍微详细点。
先来看看原始的未经过重构的代码:
public class ClassRegistration
{
public void CreateAdmin()
{
// create registration code
}
public void CreateUser()
{
// create registration code
}
public decimal Total { get ; private set ; }
}
public class RegistrationProcessor
{
public decimal ProcessRegistrationAdmin(ClassRegistration registration)
{
registration.CreateAdmin();
return registration.Total;
}
public decimal ProcessRegistrationUser(ClassRegistration registration)
{
registration.CreateUser();
return registration.Total;
}
}
protected void CreateAdmin_Click( object sender, EventArgs e)
{
RegistrationProcessor registrationProcessor = new RegistrationProcessor();
registrationProcessor.ProcessRegistrationAdmin( new ClassRegistration());
}
protected void CreateUser_Click( object sender, EventArgs e)
{
RegistrationProcessor registrationProcessor = new RegistrationProcessor();
registrationProcessor.ProcessRegistrationUser( new ClassRegistration());
}
public interface IClassRegistration
{
void Create();
decimal Total { get ; }
}
public class ClassRegistrationAdmin : IClassRegistration
{
public void Create()
{
// create registration code
}
public decimal Total { get ; private set ; }
}
public class ClassRegistrationUser : IClassRegistration
{
public void Create()
{
// create registration code
}
public decimal Total { get ; private set ; }
}
public class RegistrationProcessor
{
public decimal ProcessRegistration(IClassRegistration registration)
{
registration.Create();
return registration.Total;
}
}
protected void Create_Click( object sender, EventArgs e)
{
var btn = sender as Button;
if (btn != null )
{
RegistrationProcessor registrationProcessor = new RegistrationProcessor();
IClassRegistration registration;
switch (btn.CommandArgument)
{
case " CreateAdmin " :
registration = new ClassRegistrationAdmin();
registrationProcessor.ProcessRegistration(registration);
break ;
case " CreateUser " :
registration = new ClassRegistrationUser();
registrationProcessor.ProcessRegistration(registration);
break ;
}
}
}