Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: A design pattern for building a text file from different methods

Tags:

java

I'm building a file by appending text based on different parameters.

Lets say my file will have 3 paragraphs A, B, C, and you can build each paragraph in 3 different ways

At the end you end up with something like A1, B2, C3 or A1, B1, C1 or A2, B1, C2 and so on

I already did this with a lot of IFs, and the ugliest part was the fact that each class had parameters of the following ones. For instance A receives 3 parameters and passes 2 to B, then B passes the last one to C

This is not extensible or maintainable at all, I really feel everything is chained and I want to break the chain, so how can I implement this neatly?

like image 859
javaNoober Avatar asked May 30 '26 17:05

javaNoober


1 Answers

Ah this is a textbook case of the Strategy pattern. It allows you to have a main interface and then use that to implement concrete classes that use the same data to do different things.

The following is an example of what your code would look like in the end.

class StrategyExample {


    public static void main(String[] args) {

        Context context;

        // Two contexts following different strategies
        context = new Context(new ConcreteStrategyNumber());
        string numberedText = context.executeStrategy(text);

        context = new Context(new ConcreteStrategyLetter());
        string letteredText = context.executeStrategy(text);

    }
}

Numbered text would be something like 1 2 3 and lettered text would be something like A B C for each paragraph.

like image 167
Devin M Avatar answered Jun 02 '26 07:06

Devin M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!