Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

java - Design pattern for executing various operations depending on flags passed as arguments

For purposes of learning new technology, I want to create simple utility app that generates mathematical statistics. There are various operations that the utility can do, lets say for now there are 3 of them:

utility.sum(); utility.geometricMean(); utility.arithmeticMean();

User can request generating 3 statistics from above, depending on flags he specifies when executing app, let's say

-s -gm -am

The point is user can select any combination of N statistics, so when he runs app with -s -am flags, the app should execute utility.sum(); utility.arithmeticMean(); methods.

I am wondering, what would be an elegant design (probably using a design pattern?) of such module, that corresponds to all clean code, clean design and SOLID principles.

The flags can be represented in a way that suits the solution best - booleans, integers, enums - it does not really matter for me.

EDIT: As MrFisherman suggested, it is a good idea to implement the mathematical operations itself with Command, but im mostly concerned about HOW TO CREATE those commands depending on flags passed. Is there any way to avoid doing stuff like below?

if(flag == '-am') commands.add(new ArithmeticMeanCommand());
else if(flag == '-gm') commands.add(new GeometricMeanCommand());
else if(flag == '-s') commands.add(new CalculateSumCommand());
question from:https://stackoverflow.com/questions/65649152/design-pattern-for-executing-various-operations-depending-on-flags-passed-as-arg

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you can use Command: https://en.wikipedia.org/wiki/Command_pattern and put every action in separate class like geometricMeanCommand, arithmeticMeanCommand etc. But in your problem as our friend who delete his answer said, you can just use simple switch statement. You can also use Facade design pattern https://en.wikipedia.org/wiki/Facade_pattern and share just a couple of methods to your main method (inside you will be able to combine them in different ways).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...