Creational Patterns  «Prev  Next»
Lesson 9

Design Pattern Factory Module Conclusion

In this module you learned how creational patterns can help you make your programs more adaptable and dynamic. In particular, creational patterns allow you to defer many decisions about which classes are instantiated until runtime.
In the next module, you will learn about structural design patterns.
You will adjust the vehicle Product classes to use the Flyweight pattern, and you will see how nicely that pattern fits with the Factory Method used here. You will also notice that no changes will be required outside the Product classes to accommodate the new pattern because of the Factory Method provides a clean separation.

The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects without specifying the exact class of the object that will be created.
The creation of an object often requires complex processes which are not appropriate to include when composing an object. The object's creation may lead to
  1. a significant duplication of code,
  2. may require information not accessible to the composing object,
  3. may not provide a sufficient level of abstraction, or
  4. may otherwise not be part of the composing object's concerns.
The factory method design pattern handles these problems by
  1. defining a separate method for creating the objects,
  2. which subclasses are able to override to specify the derived type of product that will be created.


9. Given the following code:
interface Drinkable { int drink(); }
public class Mocktail {
  public int enjoy( Drinkable d ) { return d.drink(); }
  public void testDrinkable() {
	  enjoy(
	   //insert code here 15
	  );
  }
}
Which code, inserted at line 15, allows the class Mocktail to compile? [Please select 1 option: ]
  1. Drinkable { public int drink () { return 1; }
  2. new Drinkable { public int drink () { return 1; }
  3. new Drinkable() { public int drink() { return 1; }
  4. new class Drinkable { public int drink () { return 1; }


Answer: C
Explanation:
The given block of code depicts an interface Drinkable which has a drink method. There is also a class Mocktail which has a concrete method enjoy( Drinkable d) which takes a Drinkable object as parameter and in turn calls the drink() method. The method testDrinkable() calls the enjoy method. This method has to be given a Drinkable object as parameter which is possible only by giving an anonymous implementation since Drinkable is an interface. Option C creates a new anonymous object of an anonymous class implementing the Drinkable interface by giving an implementation for its drink() method. Hence, C is the correct answer. In addition, all other options have syntactical errors in the code. So, they are invalid options and are not correct answers to the problem.