How should I model my code to maximize code re-use in this specific situation?

后端 未结 7 1598
清歌不尽
清歌不尽 2020-12-11 02:26

Updated: See end of question for how I implemented the solution.

Sorry for the poorly-worded question, but I wasn\'t sure how best to ask it. I\'m not sure

相关标签:
7条回答
  • 2020-12-11 03:20

    Create an abstract base class and have the method that needs to be changed as abstract protected e.g.

    public abstract class OutboxManager 
    {
        private List<OutboxMsg> _OutboxMsgs;
    
        public void DistributeOutboxMessages()
    {
        try {
            RetrieveMessages();
            SendMessagesToVendor();
            MarkMessagesAsProcessed();
        }
        catch (Exception ex) {
            LogErrorMessageInDb(ex);
        }
     }
    
        private void RetrieveMessages() 
        {
          //retrieve messages from the database; poplate _OutboxMsgs.
          //This code stays the same in each implementation.
        }
    
        protected abstract void SendMessagesToVendor();   // <== THIS CODE CHANGES EACH IMPLEMENTATION
    
    
        private void MarkMessagesAsProcessed()
        {
          //If SendMessageToVendor() worked, run this method to update this db.
          //This code stays the same in each implementation.
        }
    
        private void LogErrorMessageInDb(Exception ex)
        {
          //This code writes an error message to the database
          //This code stays the same in each implementation.
        }
    }
    

    Each implementation inherits from this abstract class but only provides the implementation for SendMessagesToVendor() the shared implementation is defined in the abstract base class.

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