Design Patterns - what to use when the return type

2019-09-12 06:13发布

问题:

How would you architect this solution where you have different type of search, like web, image etc. So in effect the input is same but the result are different according to search type selected

I can think of Strategy n Factory to handle input and select different search algorithm but how to handle return type?

Thanks in advance

回答1:

You can either have a BaseSearchResult kind of class or have the result interfaced, so that different types of search classes can return same type of result.

Edit: you can also go with generics, something like this:

class SearchByType1<T>
{
   public T ExecuteSearch()
   {
   }
}

By base class I mean if you could have some common and essential properties of all kinds of search result you can create a baseclass and return that by executing searches, similar idea with interfaces.



回答2:

the search result could return 2 properties:

  • type of search result
  • the payload (the search result itself)

Example:

using System;

public enum SearchResultType
{
    WebPage = 1,
    Image = 2,
    Video = 3,
    Tweet = 4
}

public class SearchResult
{
    public SearchResultType SearchResultType { get; set; }
    public Object Payload { get; set; }

    public SearchResult()
    {
    }
}

the payload type can be either an Object, or a BaseSearchResultPayload abstract class from which WebPageSearchResultPayload and ImageSearchResultPayload would inherit. you could also use generics or dynamic if that suits your needs, that depends on the details and context of your app.