我有两个类,服务器和客户端。服务器需要在多个线程中实例化客户端,客户端有一个需要提供自定义实现的虚拟成员。我的问题是。Client 类应该是 Server 类的嵌套类,还是我应该使用接口和依赖注入将自定义实现放入 Server 类。现在,Client 类也有许多私有方法,它们提供了一些不应更改的标准逻辑。
public class Server
{
public void DoWork()
{
for (var i = 0;i < 10; i++)
{
Client client = new Client();
client.Process(i);
}
}
}
public class Client
{
private void doSomething()
{
...
}
// Needs to be overridden and provide custom logic
public virtual string Process(int i)
{
return i.ToString();
}
}
工作示例:
public interface IClient
{
string Process(string message);
}
public abstract class Client : IClient
{
public virtual string Process(string message)
{
return message;
}
}
public class CustomClient : Client
{
public CustomClient() { }
public override string Process(string message)
{
return string.Format("Custom Client:{0}", message);
}
}
public class Server
{
private Func<IClient> createClient;
public Server() { }
public Server(Func<IClient> client)
{
createClient = client;
}
public void DoWork()
{
for (var i = 0; i < 10; i++)
{
IClient = client = createClient();
client.Process(string.Format("Client #{0}", i));
}
}
}
测试程序...您将逐步查看它是否命中了 CustomClient
class Program
{
static void Main(string[] args)
{
Func<CustomClient> factory = () => new CustomClient();
var server = new Server(factory);
server.DoWork();
}
}