Replace conditional with polymorphism - nice in theory but not practical

后端 未结 9 1540
时光说笑
时光说笑 2020-12-24 01:52

\"Replace conditional with polymorphism\" is elegant only when type of object you\'re doing switch/if statement for is already selected for you. As an example, I have a web

9条回答
  •  臣服心动
    2020-12-24 02:54

    public abstract class BaseAction
    {
        public abstract void doSomething();
    }
    
    public class ViewAction : BaseAction
    {
        public override void doSomething() { // perform a view action here... }
    }
    
    public class EditAction : BaseAction
    {
        public override void doSomething() { // perform an edit action here... }
    }
    
    public class SortAction : BaseAction
    {
        public override void doSomething() { // perform a sort action here... }
    }
    
    
    string action = "view"; // suppose user can pass either
                            // "view", "edit", or "sort" strings to you.
    BaseAction theAction = null;
    
    switch (action)
    {
        case "view":
            theAction = new ViewAction();
            break;
    
        case "edit":
            theAction = new EditAction();
            break;
    
        case "sort":
            theAction = new SortAction();
            break;
    }
    
    theAction.doSomething();
    

    So I don't need conditionals here, but I still need it to decide which BaseAction type to instantiate first. There's no way to completely get rid of the conditionals.

提交回复
热议问题