我正在研究这种模式,我想执行一个方法,但我不知道如何调用它,因为这些参数化构造函数对我来说似乎很复杂。我所遵循的代码由两个接口和两个类组成。下面是示例代码。请帮我如何调用“TestMethod()”。如果可能,有人可以帮助我实现以下目标。
控制台应用
class Program
{
private static IPropertyService _property;
public Program(IPropertyService property)
{
_property = property;
}
static void Main(string[] args)
{
Console.WriteLine("Enter something...");
_property.TestMethod(Console.ReadLine());
Console.ReadLine();
}
public interface IPropertyService
{
string TestMethod(string strParam);
}
private class PropertyService : IPropertyService
{
private readonly IPropertyRepository _propertyRepository;
public PropertyService(IPropertyRepository propertyRepository)
{
_propertyRepository = propertyRepository;
}
public string TestMethod(string strParam)
{
return _propertyRepository.TestMethod(strParam);
}
}
}
public interface IPropertyRepository
{
string TestMethod(string strParam);
}
public class PropertyRepository : IPropertyRepository
{
public string TestMethod(string strParam)
{
return string.Format("You have entered: {0}", strParam);
}
}
答案 0 :(得分:1)
计划是您的入门级课程。不要使它成为参数化的构造函数。它不起作用。
public Program(IPropertyService property)
您无需将IPropertyService
定义为私有静态方法。在Main方法中本地声明它就可以了。
static void Main(string[] args)
{
Console.WriteLine("Enter something...");
IPropertyService _property = //to be added;
_property.TestMethod(Console.ReadLine());
Console.ReadLine();
}
现在让我们谈谈//to be added
部分。
在这种情况下,到目前为止最简单的解决方案是使用Abstract Factory。手动编码的示例:
public class PropertyServiceFactory{
public IPropertyService Create(){
IPropertyRepository repository = new PropertyRepository();
PropertyService service = new PropertyService(repository);
return service;
}
}
实施:
Console.WriteLine("Enter something...");
PropertyServiceFactory factory = new PropertyServiceFactory();
IPropertyService _property = factory.Create();
_property.TestMethod(Console.ReadLine());
但是,如果您想要破坏PropertyServiceFactory和PropertyRepository之间的依赖关系,请将您的工厂修改为:
public class PropertyServiceFactory{
private readonly IPropertyRepository _repository;
public PropertyServiceFactory(IPropertyRepository repository){
_repository = repository
}
public IPropertyService Create(){
PropertyService service = new PropertyService(_repository);
return service;
}
}
有了这个,你已经解耦了PropertyServiceFactory和PropertyRepository。实施是:
Console.WriteLine("Enter something...");
IPropertyRepository repository = new PropertyRepository();
PropertyServiceFactory factory = new PropertyServiceFactory(repository);
IPropertyService _property = factory.Create();
_property.TestMethod(Console.ReadLine());
Mark Seemann的信用