Joe
Joe

Reputation: 8042

Succinct expression of Strategy Pattern in Java

I want to use the strategy pattern in Java. However, my boss doesn't like it if I add lots of files to the code base or write verbose code. It seems that with the strategy pattern I'd have to make one file for an interface and then five additional files so I can have a class for each of my five possible strategies.

Is there a way to express the strategy pattern in Java with fewer files and less code?

I think it would be ideal if my strategy variations could be represented on an Enum or one Set that is easy to assemble.

Upvotes: 0

Views: 172

Answers (1)

Matt
Matt

Reputation: 11805

I think you should sit down with your boss and explain to him/her that less files != good code. At least attempt to explain the pattern itself and how having multiple classes, each with it's own specific purpose is better for testing, maintenance, etc....

Personally, i find code more verbose with lots of IF statements littered about the place where proper polymorphism would make the code much easier to understand.

PS: And yes, enums can have behavior by using the anonymous subclassing construct:

public enum Foo {
   BAR() {
     public void baz() { ... }
   };

   public abstract void baz();
}

Though i'm not sure i'd recommend using that unless you absolutely have to.

Upvotes: 1

Related Questions