有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

设计模式在Java中建模动作

我希望使用设计模式来标准化常见操作,但我不确定哪一个是最好的

假设我们从两个服务Java类开始,每个类有两个操作/方法

class Service1 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

class Service2 {
    public void performSomething() {
        // Some complex algorithm implemented here
    }
    public void performSomethingElse {
        // Some complex algorithm implemented here
    }
}

两个服务共享相同的算法,所以很自然,我想重构performSomething()performSomethingElse()。我的方法是为每个重构方法创建两个单一的方法类

interface Action {
    public void run();
}
class PerformSomething implements Action {
    public void run() {}
}
class PerformSomethingElse implements Action {
    public void run() {}
}

class Service1 {
    private PerformSomething algo1;
    private PerformSomethingElse algo2;

    public void businessUseCase1() {
        algo1.run();
        algo2.run();
    }

}

我觉得这种简单的方法很幼稚,我非常确定有一种更合适的设计模式可以表示一个动作,而不是创建一个自定义接口来表示动作


共 (1) 个答案

  1. # 1 楼答案

    考虑到亲吻和春天,我会做以下几件事:

    @Service
    class Service1 {
        public void performSomething() {
            // Some complex algorithm implemented here
        }
        public void performSomethingElse {
            // Some complex algorithm implemented here
        }
        public void businessUseCase1() {
            performSomething();
            performSomethingElse();
        }
    
    }
    
    @Service
    class Service2 {
        @Autowired
        Service1 service1;
    
        public void performSomething() {
            // Some complex algorithm implemented here
        }
        public void performSomethingElse {
            // Some complex algorithm implemented here
        }
        public void businessUseCase1() {
            service1.performSomething();
            service1.performSomethingElse();
            // or
            service1.businessUseCase1();
        }
    
    }