18
Chaper 4 Notes – Factory Method Pattern Introduction All “factory” patterns are concerned with creating objects. Here, we consider three cases: a. Simple Factory – not a pattern, but useful. b. Factory Method c. Abstract Factory (considered in next set of notes and the second half of Chapter 4 HFDP. Text Discussion 1. What is the problem with code that uses lots of concrete classes? What is a better solution? 2. Page 111 tells us to remember the design principle that tells us to identify the aspects that vary and separate them from the things that stay the same. In the example on pages 112-113, what is varying? 3. What is a Simple Factory class? 4. What is a disadvantage of making the createPizza() method static? 5. On page 116, we see that the PizzaStore class is composed with a SimplePizzaFactory which follows one of our design principles to favor composition over inheritance. What design principle does it violate? 6. Suppose that you have a system that creates a group of objects from one class. For testing purposes it is useful to create these objects with attributes set to specific values. How can the Simple Factory help with this? 7. Describe what it means to say that the subclasses are deciding which pizzas to make. 8. How does the factory method pattern decouple the pizza store from pizzas? 9. Discuss how the factory method can be thought of as supplying a framework. 10. What is a parameterized factory method? 11. Discuss the difference between the simple factory and the factory method. Simple Factory 1

Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

Chaper 4 Notes – Factory Method Pattern

Introduction

All “factory” patterns are concerned with creating objects. Here, we consider three cases:

a. Simple Factory – not a pattern, but useful.b. Factory Methodc. Abstract Factory (considered in next set of notes and the second half of Chapter 4 HFDP.

Text Discussion

1. What is the problem with code that uses lots of concrete classes? What is a better solution?2. Page 111 tells us to remember the design principle that tells us to identify the aspects that vary and

separate them from the things that stay the same. In the example on pages 112-113, what is varying?3. What is a Simple Factory class?4. What is a disadvantage of making the createPizza() method static?5. On page 116, we see that the PizzaStore class is composed with a SimplePizzaFactory which follows

one of our design principles to favor composition over inheritance. What design principle does it violate?

6. Suppose that you have a system that creates a group of objects from one class. For testing purposes it is useful to create these objects with attributes set to specific values. How can the Simple Factory help with this?

7. Describe what it means to say that the subclasses are deciding which pizzas to make.8. How does the factory method pattern decouple the pizza store from pizzas?9. Discuss how the factory method can be thought of as supplying a framework.10. What is a parameterized factory method?11. Discuss the difference between the simple factory and the factory method.

Simple Factory

1. The simple factory is described as an idiom. It adheres to the design principle that we should separate the things that vary from the things that stay the same. It also adheres to the design principle of increasing cohesion. The simple factory idiom simply says that anytime object creation involves more than a few steps, we should factor out this creation into its own class. Many times the simple factory has static methods for creating objects, although it doesn’t have to, as shown in the UML below.

1

Page 2: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

2. The BorderFactory is a simple factory found in the Java API which has static methods for creating various borders. It also serves as a Façade to the Borders.

a. See BevelBorder class. Look at constructors.

BevelBorder(int bevelType)Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method.

BevelBorder(int bevelType, Color highlight, Color shadow)Creates a bevel border with the specified type, highlight and shadow colors.

BevelBorder(int bevelType, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor)Creates a bevel border with the specified type, highlight and shadow colors.

b. See BorderFactory class. Look at createRaisedBevelBorder method.

static Border createRaisedBevelBorder()Creates a border with a raised beveled edge, using brighter shades of the component's current background color for highlighting, and darker shading for shadows.

2

Page 3: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

c. (Incorrect, needs fixing-Spring 14) Could you subclass BorderFactory and override the static methods? Yes and No. Java doesn’t stop you from overriding static methods, but the behavior depends on the reference type, not the actual run-time time as in overridden instance methods. For instance:

BorderFactory bf = new BorderFactory();Border b = bf.createRaisedBevelBorder();

Would produce the same border as:

BorderFactory sbf = new SubBorderFactory();Border sb = sbf.createRaisedBevelBorder();

However, this would produce a different border:

SubBorderFactory sbf2 = new SubBorderFactory();Border sb2 = sbf.createRaisedBevelBorder();

3. The problem with the simple factory is that when we create new products, we must modify the simple factory.

4. Two other simple factories are: BasicIconFactory, ColorChooserComponentFactory.

3

Page 4: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

Factory Method Pattern

1. The factory method pattern is simply an abstraction of the simple factory which allows new products to be added without modifying the factory. By doing so, it adheres to the design principle of programming to an interface, not an implementation.

2. The Factory Method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

The intent of the Factory Method pattern is to relieve a client from having to know which class to instantiate.

Many times, as shown in the UML above, the Client calls a method that creates and manipulates a product, but doesn’t actually create the product directly.

Client c = new Client( new ConcreteCreator );c.anOperation();

4

Page 5: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

3. The example from the text shows that the driver calls the orderPizza (template) method which creates (factory method) and builds a pizza, and then returns it. The factory method is createPizza which is called by the orderPizza method.

5

Page 6: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

Factory Method in Java

1. The iterator method specified in the Collection interface is a FactoryMethod. The Collection interface says that any class that wants to be a “Collection” must specify an iterator method that returns an Iterator.

See the code in ArrayList class, lines 773, 780:http://www.docjar.com/html/api/java/util/ArrayList.java.html

In other words, a Client has some sort of Collection and uses an Iterator:

This allows us to write polymorphic methods such as the one below. It can process a collection of Employee objects, such as HashSet, LInkedList, PriorityQueue, or a custom collection.

private static void processEmployees( Collection<Employee> c ) { Iterator<Employee> iter = c.iterator(); while( iter.hasNext() ) { Employee e = iter.next(); System.out.println( e ); } }

6

Page 7: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

2. Java provides a DataSource interface that provides a specification for a Factory Method, getConnection for use in accessing data bases. Vendors supply classes that implement the DataSource interface, thus an implementation for getConnection which returns a Connection object for that particular Vendor’s product. Thus, clients can be coded against the Connection interface and not have to even be aware of the concrete connection class.

3. ContentHandler’s are used to get the content from the URLConnection. The Java interface ContentHandlerFacotry has a factory method, createContentHandler which returns a ContentHandler (abstract product) for a specified MIME type (e.g. gif, text, etc). The ContentHandler has a method which provides a getContent method which returns the content of a URLConnection.

4. The TableCellRenderer is a factory interface with a factory method: getTableCellRedererComponent used for drawing a cell in a JTable. The DefaultTableCellRenderer class implements this interface and is used for simple JTables. An Example.

7

Page 8: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

Generic Editor Example

1. Consider the Generic Editor that illustrates the Factory Method pattern as found in:http://www.java2s.com/Code/Java/Design-Pattern/FactoryMethodPatterninJava.htm

One concrete factory produces a “Contact” editor:

Another concrete factory produces an “Employee” editor:

2. Consider the design:

8

Page 9: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

3. Consider the design in terms of the Factory Method:

4. The EditorGui class is the main class. It creates a JFrame and displays it. The JFrame contains a JPanel that contains an ItemEditor (product) which knows how to display itself and how to save changes. To create the “Contact” editor:

// Create factory Editable contact = new Contact(); // Create product ItemEditor editor = contact.getEditor(); // Create gui class instance EditorGui contactEditor = new EditorGui( editor ); // Build gui contactEditor.createGui();

The createGui method has code like this . . .

editorPanel = new JPanel();editorPanel.add(editor.getGUI());

9

Page 10: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

5. Consider the class diagram

6. It works like this:

a. Create an Editable (Factory) which is either the Contact class or the Employee class. Notice that these classes have fields for the values that are displayed.

b. Call the factory method, getEditor that creates an ItemEditor (Product) which is either a ContactEditor or an EmployeeEditor, respectively. Notice that the products have a getGui method that builds a gui for the fields that need to be edited. Notice also that when the ItemEditor is created, it creates a reference back to its creator (Factory). This is so that when the editor’s commitChanges method is called, the values are store in the factory!

c. Pass the editor (Product) to the constructor of the EditorGui class. d. The EditorGui’s createGui method is called, it creates a JFrame with an empty JPanel and then calls

editor.getGui to return a JPanel filled with Contact (or Employee) information. This filled JPanel is then placed in the JFrame’s JPanel.

e. The GUI allows the fields to be edited and provides a “Update Item” button. When this button is pressed, the editor’s commitChanges method is called which saves the changes back to the Contact (or Employee) object (e.g. the factory).

10

Page 11: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

Data Persistence – Data Access Object (DAO)

1. Data Persistence

Source: http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

A common problem is that you have a business object that needs to persist data to a data store. If the code to handle the persistence is embedded in the business object, then the class is not cohesive. In other words, it has more than one purpose. It fulfills its responsibilities for manipulating the data and for persisting the data. Also, the data persistence code is likely to change as we port the code to new environments.

2. A solution is to introduce a DataAccessObject (DAO) which encapsulates the data persistence. The DAO is a simple factory. It creates a TransferObject (typically a domain class, e.g. Customer, etc.) to carry data back and forth from the data store.

3. The sequence diagram shows the typical operation:

11

Page 12: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

4. The problem with this approach, is that it doesn’t completely solve the portability problem. If we abstract further, we arrive at the Factory Method Pattern. Here, we define a DAO interface which we program against. Concrete DAO’s can then be plugged in to solve the portability problem.

5. Finally, we show an even more general approach that relies on the Factory Method pattern. In this case, we show multiple factory methods. This is blurring the line between the Factory Method pattern and the Abstract Factory, which we consider later. This example will be continued as we explore that pattern.

References

1. Wikipedia - Good description.2. DOF - Document Creation

12

Page 13: Chaper 1 Questions - Valdosta State University€¦ · Web viewChaper 4 Notes – Factory Method PatternIntroduction All “factory” patterns are concerned with creating objects

3. WinDevCenter - Lots of examples in .net Framework Class Library (FCL).4. Gamelan - Excrypted sockets.5. Maze - Maze example6. ACM - Article about implementing factory method so as to use the least energy in a mobile device.7. Java2s - Generic GUI editor.

13