Hello World in Design Patterns



I would like to claim that this is my creation but to be honest I stole it from a post on Slashdot. It nicely shows how the Overdesign Design Pattern works.

First the code that simple-minded programmers would type:

public class HelloWorld
{
   public static void main(String[] args)
   {
      System.out.println("Hello, world!");
   }
}

- ugly, unstructured and it's obvious that the programmer had no concerns of what the future might bring what-so-ever, right?

This is the way real programmers do it:

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 (null==instance) 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);
   }
}

Comments