How can I design this better? (Avoiding a switch statement with Object Oriented design)

前端 未结 6 821
不思量自难忘°
不思量自难忘° 2020-12-30 11:23

I know a little bit about Object Oriented design, but I\'m not sure how to go about using those principles in my code. Here\'s what I\'m working on:

    pub         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 11:54

    Is Agency a class you control? If so do something like this:

    public abstract class GenericDb
    {
        public abstract void Query(parms);
    }
    

    In your Agency Class, you could have

    public GenericDb ClientDb {get; set;}
    

    Then have a SqlDb class like:

    public class SqlDb : GenericDb
    {
        public void Query(parms);
    }
    
    public class PicDb : GenericDb
    {
        public void Query(parms);
    }
    

    Then this code:

    public void Query(Agency agency, Citation queryCitation) {
            queryCitation.AgencyCode = agency.AgencyCode;
    
            switch (agency.ClientDb.Type) {
                case "SQL":
                    QueryOracle(agency, queryCitation);
                    break;
                case "PIC":
                    QueryPick(agency, queryCitation);
                    break;
            }
        }
    

    becomes

    public void Query(Agency agency, Citation queryCitation) {
            queryCitation.AgencyCode = agency.AgencyCode;
            agency.ClientDb.Query(queryCitation);
        }
    

    Because of inheritance, it will know that ClientDb has a base class of GenericDb. It will know by the type of the ClientDb parameter whether it should run the SqlDb or the PicDb or Oracle etc.

提交回复
热议问题