Question

I have different kinds of Quotes, like Boat quote, Motorcycle quote, CarQuote which all derive from Quote class. When a client wants to get quote I need to just return Quote. I can implement in two ways:

Factory:

public class QuoteFactory{
     public Quote GetQuote(string QuoteType )
     {
      if(quoteType = "car")
         {
           return new CarQuote()
        }
     }

DI with Spring.Core

Add all the quote types to Context and then let client decides which type is needed. Thanks in advance.

Was it helpful?

Solution 2

What is the point of that method if all you require is a quote. The calling method knows what type of quote it wants - it has to as your passing it in as parameter. If you genuinely want to abstract the creation of the quote into an injectable class (for unit testing for example) why not create a generic method eg:

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();
    }
}

OTHER TIPS

Not sure about your question, but this is the refactored factory using 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
    }
}

Using this design you can depend on DI Container to handle the constructor injections. Moreover, you can replace this design by injecting IDictionary<string, Quote> instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top