开发者

Design question - template pattern with enum implementing an interface

开发者 https://www.devze.com 2023-03-09 17:25 出处:网络
My code is starting to look out of control so I thought I would ask for help. I have an enum class that implements an interface. The first thing the method does is get a db connection from a pool usi

My code is starting to look out of control so I thought I would ask for help.

I have an enum class that implements an interface. The first thing the method does is get a db connection from a pool using jndi. Then based on the objects properties performs a series of calculations and returns a result.

public interace MyInterface {  
     public ResultObject calculate(MyObject myObject); 

}

public enum MyEnum implements Myinterface {
    public ResultObject calculate(MyObject myObject) {
         //several steps
    }
}

This has been working fine with only one calculation. I now have a few more ways to calculate with just a few changes needed for each calcul开发者_如何学JAVAation.

The template method design pattern sounds perfect for this but I am confused on how I can make it work with the enum implementation I currently have? I don't want to add a bunch of branch statements in my enum calculate method and make it hard to maintain.

I am using spring mvc and I have a controller for each calculation that extends a base class. I call super.calculate() in each controller and I would like to keep this the same.

Does anyone have any suggestions for this scenerio? I feel like when I started the design was good but now I am not so sure.


I find it really confusing that you would have an enum that implements an interface like this, especially if the enum is responsible for interacting with a database - sounds like you may be misusing enums.

As for the actual problem, I would create a base class (potentially abstract) which contains the core logic of the calculate(MyObject) method and delegates the "additional ways" to calculate to either an abstract method or a protected method override-able by subclasses, so that you can have slightly different implementations of MyInterface which provide the different behavior.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号