solutions served

Technology and Business Talks
01 Dec 2015
by Oluwasayo Oladeji

What is the difference between the Facade and Factory design patterns?

Answer by Sayo Oladeji:

A Factory produces objects (based on some specifications).

public class Block {
 // Properties: length, breadth, height, geometry, volume, surface_area, etc.
}

public class BlockFactory {
    public static final Block create(Equation... eqns, Texture texture) {
        // Do deep magic.
        return block;
    }
}

A Facade is an appealing gateway to a rather unappealing interaction of objects.

interface BackOffice {
    BigDecimal accountBalance(Long walletId);
    void debit(Long walletId, BigDecimal amount);
    void credit(Long walletId, BigDecimal amount);
    BigDecimal price(Long itemId);
    BigDecimal tax(Long itemId);
    void removeInventory(Item... items);
    TrackingDetails ship(Address address, Item... items);
}

public class StoreFront {

   // Inject these somehow.
   BackOffice bo;
   SessionContext context;

   public Response purchase(ShoppingCart cart) {
      // Transaction starts.
      User user = context.getUser();
      BigDecimal total = BigDecimal.ZERO;
      for (Item item : cart.getItems())
          total = total.plus(bo.price(item.getId())).plus(bo.tax(item.getId()));

      if (bo.accountBalance(user.getWalletId()).compareTo(total) < 0)
         throw new InsufficientBalanceException();
      
      wallet.debit(total);
      removeInventory(cart.getItems());
      TrackingDetails td = ship(user.getAddress(), cart.getItems());
      
      return Response.success(td);
      // Transaction ends.
   }
}

You see the complex interaction hidden by the

StoreFront.purchase()

facade?

What is the difference between the Facade and Factory design patterns?

© 2014. Hextremelabs