Thursday, March 13, 2014

Design Patterns

Design Patterns:


Factory, Singleton, Prototype and Builder Patterns:

[Cracking the Coding Interview]
Because interviewers are trying to test your capabilities and not your knowledge, design patterns are mostly beyond the scope of an interview. However, the Singleton and Factory Method design patterns are widely used in interviews, so we will cover them here. There are far more design patterns than this book could possibly discuss. A great way to improve your software engineering skills is to pick up a book that focuses on this area specifically. Be careful you don't fall into a trap of constantly trying to find the "right" design pattern for a particular problem. You should create the design that works for that problem. In some cases it might be an established pattern, but in many other cases it is not. 
Singleton Class The Singleton pattern ensures that a class has only one instance and ensures access to the instance through the application. It can be useful in cases where you have a "global" object with exactly one instance. For example, we may want to implement Restaurant such that it has exactly one instance of Restaurant. 
1 public class Restaurant { 
2 private static Restaurant _instance = null; 
3 protected Restaurant() { ... } 
4 public static Restaurant getlnstance() { 
5 if (_instance == null) { 
6 _instance = new Restaurant(); 
7 } 
8 return _instance; 
9 } 
10 }
 It should be noted that many people dislike the Singleton design pattern, even calling it an "anti-pattern:' One reason for this is that it can interfere with unit testing. 
Factory Method The Factory Method offers an interface for creating an instance of a class, with its subclasses deciding which class to instantiate. You might want to implement this with the creator class being abstract and not providing an implementation for the Factory method. Or, you could have the Creator class be a concrete class that provides an implementation for the Factory method. In this case, the Factory method would take a parameter representing which class to instantiate. 
1 public class CardGame { 
2 public static CardGame createCardGame(GameType type) { 
3 if (type == GameType.Poker) { 
4 return new PokerGame(); 
5 } else if (type == GameType.BlackJack) { 
6 return new BlackJackGame(); 
7 } 
8 return null; 
9 } 

10 }

No comments:

Post a Comment