Friday, January 9, 2015

Make OO Design Patterns Simple

I am a person who wants to make complex simple. There are tons of thick books about OO design patterns, but I prefer starting with the most commonly used ones.

First of all, why do we need design pattern? Generally, understanding OO design patterns could help you better plan your design stage before rushing to coding. Now let's see the following common patterns.

1. Facade

When you have a complex subsystem, you'd better use one simple interface to the subsystem by hiding the in-system classes in one black-box class.
For example, a QR code scanner subsystem of our smartphone may include many classes, however, a developer who wants to use the scanner subsystem may just need a simple facade class to return the result (e.g. decoded content).

2. Strategy

If we believe that an object may use different strategies for doing a task, we can set slots for the strategy module.
For example, we need to develop a robot that can recommend different recipes as per the age, weather,  planned activities in the next 6 hours and other conditions. Then the first step is to define an interface, Strategy, and have it implemented in different strategy classes.
We then pass a Strategy object to the Robot's constructor and provide a method (setStrategy) in Robot that sets its strategy. The setStrategy can be called from main or another higher-level class.

3. Singleton

Suppose we create a CoinMaker object mycoin in a game, so how can we give other classes access to mycoin by making the CoinMaker instance accessible to clients?
public class MyCoinHandle
{ private static CoinMaker myCoinStat;
   protected MyCoinHandle() {}
   public static CoinMaker getMyCoin(String myName)
   { if (myCoinStat == null)
        myCoinStat = new CoinMaker(myName);
      return myCoinStat;
Now other method can use all CoinMaker's methods. For example:
  CoinMaker tom = MyCoinHandle.getMyCoin("Thomas Obama");

No comments:

Post a Comment