【问题标题】:Which programming pattern is preferred首选哪种编程模式
【发布时间】:2018-01-07 12:22:15
【问题描述】:

如果我有一个类,其中的所有函数都需要先通过检查,以下哪个更优选

1.

class check{
   public check(Status){
    if(CheckFunc(Status)){
       // Passed the Check function and return a class instance
       return new UpdateClass();
    }
}

class UpdateClass{
   public void Func1(){     
    // Do the stuff
   }
   // Other functions...
}

2.

class UpdateClass{
    boolean passedCheck = false;
    public UpdateClass(Status){
        if(checkFunc(Status)){
            this.passedCheck = true;
        }
    }
    public void Func1(){
        if(this.passedCheck){
        // Do the stuff
        ...
        }
    }
    // Other functions...
}

另外,使用类/函数来决定要实例化哪个类是一种好方法吗?

例如:

    public Animal decideWhichClass(Status){
        if(Status == StatusA){
            return new Dog();
        }
        else if (Status == StatusB){
        return new Cat();
        }
    }

    Animal a = decideWhichClass(CurrentStatus);

【问题讨论】:

    标签: design-patterns


    【解决方案1】:

    第一个问题)检查是更新处理的要求。
    在第一种方式中,您没有此保证,因为 UpdateClass 可能会在未通过检查的情况下创建和使用。

    第二个更好,因为它可以防止绕过检查:

    public UpdateClass(Status){
        if(checkFunc(Status)){
            this.passedCheck = true;
        }
    }
    

    另外,使用类/函数来决定哪个类是一种好方法吗? 实例化?

    这个例子很宽泛,但是有一个factory 的对象是可以接受的,其实例化的子类依赖于一个特定的参数。
    请注意,为避免 if/elseIf,该函数可能依赖于 Map 结构。
    这是 Java 中的一个示例(但您可以在任何对象语言中得到类似的东西):

    public class AnimalFactory{
    
       private static Map<Status, Supplier<Animal>> map = new HashMap<>();
    
       private AnimalFactory(){      
       }
    
       static {
         map.put(Status.A, Dog::new);
         map.put(Status.B, Cat::new);
       }
    
       public static Animal ofAnimal(Status status){ 
         return map.get(status).get(); 
         // of course you should also handle the error case : no association found
       }
    }
    
    
     //Client code
    Animal a = AnimalFactory.ofAnimal(Status.B);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 2010-09-16
      • 2013-07-17
      • 1970-01-01
      相关资源
      最近更新 更多