Looking for a “selective” design pattern to avoid if-elses

前端 未结 1 1582
你的背包
你的背包 2021-01-15 20:22

I have the following CSV entries:

2014-05-19 02:33:36,590,MGW,5147014,3056260212,ONNET,IN,CALL,95
2014-05-19 02:33:37,139,MGW,8827533,923049586878,ONNET,IN,N         


        
相关标签:
1条回答
  • 2021-01-15 21:13

    Using different classes to carry out the same task with different algorithms is the Strategy pattern, but the Gang of Four's original definition of the Strategy pattern doesn't deal with selecting strategies. That comes up all the time and I'd handle it like this:

    Write a class -- let's call it a Creator -- for each type of CSV line with a method create! that checks to see if the line matches the class's type, parses the line (maybe a superclass will be helpful here), saves the entry in the database and returns it. If the Creator doesn't match the line, create! just returns nil.

    Then, in the "conveyer":

    lines.each do |line|
      [RedirectedCreator, CallCreator, AlertCreator].each |creator|
        if creator.new.create! line
          break
        end
      end
    end
    

    If the process of saving the entry to the database isn't specific to the type of line, you could have your strategy classes just parse the line and return a parsed form, and let the caller do the saving in one place.

    Another variant of this pattern is for the strategy class to have a method accepts? that takes the item to be worked on and returns true or false without actually doing anything to it, and a second method that actually does the work.

    0 讨论(0)
提交回复
热议问题