我有不同类型的行情,比如船报价,摩托车报价,CarQuote都来自Quote类。当客户想要获得报价时,我需要返回Quote。 我可以用两种方式实现:
工厂:
public class QuoteFactory{
public Quote GetQuote(string QuoteType )
{
if(quoteType = "car")
{
return new CarQuote()
}
}
DI with Spring.Core
将所有引用类型添加到Context,然后让客户端决定需要哪种类型。 提前谢谢。
答案 0 :(得分:1)
不确定您的问题,但这是使用DI的重构工厂:
public class QuoteFactory : IQuoteFactory{
public QuoteFactory(Quote boatQ, Quote motorQ, Quote carQ){
// parameter assignment
}
Quote boatQ;
Quote motorQ;
Quote carQ;
public Quote Create(string quote){
if(quote == "car") return carQ;
//further condition
}
}
使用此设计,您可以依赖DI Container来处理构造函数注入。此外,您可以通过注入IDictionary<string, Quote>
代替此设计。
答案 1 :(得分:0)
如果您需要的只是一个引用,该方法的重点是什么。调用方法知道它想要什么类型的引用 - 它必须作为参数传递它。如果您真的想将引用的创建抽象为可注入类(例如,对于单元测试),为什么不创建一个通用方法,例如:
public class QuoteFactory : IQuoteFactory
{
public TQuote CreateQuote<TQuote>()
where TQuote : new() // or Quote if specific attributes requied to be set by factory
{
return new TQuote();
}
}