Wednesday, August 6, 2008

Hello, World!

<sarcastic>Ever came within an ace of understanding those damned patterns, but never really got them? Here's your solution: the classic and boring Hello World refactored to patterns - the ultimate experience!</sarcastic>

public interface MessageStrategy {
public void sendMessage();
}

public abstract class AbstractStrategyFactory {
public abstract MessageStrategy createStrategy(MessageBody mb);

}

public class MessageBody {

Object payload;

public Object getPayload() {
return payload;
}

public void configure(Object obj) {
payload = obj;
}

public void send(MessageStrategy ms) {
ms.sendMessage();
}
}

public class DefaultFactory extends AbstractStrategyFactory {

private DefaultFactory() {
;
}

static DefaultFactory instance;

public static AbstractStrategyFactory getInstance() {
if (instance == null) {
instance = new DefaultFactory();
}
return instance;
}

public MessageStrategy createStrategy(final MessageBody mb) {
return new MessageStrategy() {
MessageBody body = mb;

public void sendMessage() {
Object obj = body.getPayload();
System.out.println((String) obj);
}
};
}
}

public class HelloWorld {

public static void main(String[] args) {
MessageBody mb = new MessageBody();
mb.configure("Hello World!");
AbstractStrategyFactory asf = DefaultFactory.getInstance();
MessageStrategy strategy = asf.createStrategy(mb);
mb.send(strategy);
}
}

The original post is here. Let me add a disclaimer for the overexcited with their eyes rolling, thrilled about the whole thing and eager to refactor all their codebase: don't try this at home.

No comments: