Design Patterns - what to use when the return type is different

别来无恙 提交于 2019-12-25 16:51:57

问题


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.



来源:https://stackoverflow.com/questions/23860758/design-patterns-what-to-use-when-the-return-type-is-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!