Replace conditional with polymorphism - nice in theory but not practical

后端 未结 9 1522
时光说笑
时光说笑 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:50

    You can store string and corresponding action type somewhere in hash map.

    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;
    
    theAction = actionMap.get(action); // decide at runtime, no conditions
    theAction.doSomething();
    

提交回复
热议问题