Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 17 Abstract Factory Summary prepared by Kirk Scott 1.

Similar presentations


Presentation on theme: "Chapter 17 Abstract Factory Summary prepared by Kirk Scott 1."— Presentation transcript:

1 Chapter 17 Abstract Factory Summary prepared by Kirk Scott 1

2 2

3 3

4 4

5 Design Patterns in Java Chapter 17 Abstract Factory Summary prepared by Kirk Scott 5

6 The Introduction Before the Introduction The book provides several examples of abstract factory with context Sometimes the context seems to obscure the basic pattern The overheads will try to distinguish between the background information and the pattern 6

7 The Book’s Definition of the Pattern Book definition: The intent of the Abstract Factory, or Kit, is to allow creation of families of related or dependent objects. 7

8 Comment mode on, 1: Even though the pattern name includes the word abstract, the book’s examples don’t include an abstract class Instead, the examples show a concrete superclass and a subclass of it It would be possible to do the same thing with an abstract class and two concrete subclasses 8

9 Comment mode on, 2: The book examples show using an abstract factory to help develop a user interface Parts of this chapter are related to some of the ideas that came up with facades The example abstract factory can viewed as sort of a façade into the Java API, making its GUI elements easier to use It is a façade that is limited to creating objects 9

10 Background for the Book’s Example The book starts the example this way: In a base UI class you define methods that will return instances of graphical user interface components that have certain features 10

11 For example, an application may require a button Rather than having the application construct an instance of JButton directly, it acquires a JButton object by calling a UI method The method that constructs the JButton takes care of the construction parameters that will be used for the button 11

12 This grows into the Abstract Factory design pattern in this way: What if you would like it to be possible for the application to seamlessly use JButtons of a different form? Then you extend the UI class, overriding those methods that create objects so that the visual aspects of the objects are changed 12

13 If the application is typed to use references of the UI superclass, it can also use objects of the UI subclass What kind of JButton the client gets depends on which UI class it uses It will get the kind of JButton returned by the method in that UI class 13

14 Factory Method and Abstract Factory A very large scale way of seeing what’s going on is this: With a factory method, you wanted something that implemented an interface. A number of classes satisfied this requirement, and the logic for deciding what to give the client was in the service code. 14

15 With abstract factory, there is a hierarchy of classes containing sets of overridden methods that return various objects Each of the methods is basically a factory method Each method will return an object that meets the requirement of the client. 15

16 The client may request which member of the family of classes it would like to make use of With this choice, a set of methods becomes a available Which kind of object comes back from a method call depends on the implementation of the method in the class that was chosen 16

17 Builder, Factory Method, and Abstract Factory Abstract factory falls in a spectrum with the builder and factory method patterns. With builder, a method call returned one kind of desired, specified object. With factory method, a method call returned a reference to one of a set of kinds of objects back, with no control over which one. 17

18 With abstract factory it is possible to specify which one of a set of methods for generating objects is desired. Those methods may be simple methods where the return type is a simple class reference. Those methods may also be factory methods which return objects which agree with a required supertype, but which may actually be instances of a subtype. 18

19 A Classic Example: GUI Kits A GUI kit is an implementation of the Abstract Factory design pattern The GUI kit supplies components to client applications These components are things like buttons or other graphical user interface components The kit constructs the component objects, passing in parameters so that together the objects have a consistent look and feel 19

20 A simple illustration of the abstract factory idea is given in the UML diagram on the next overhead The UI class implements create() methods that have to do with the visual appearance of an application The diagram includes a subclass, BetaUI The same set of methods would be provided in the subclass, but they would return objects with different visual characteristics 20

21 21

22 It might be a fuller illustration of the pattern overall if there were an abstract superclass AbstractUI Then this could have multiple subclasses, including NormalUI and BetaUI However, the book has chosen to do it with a simple superclass and subclass, so the example will be pursued in that way 22

23 BetaUI inherits from NormalUI, overriding methods to create a different user interface The UML diagram on the following overhead illustrates the idea that a client application has a reference to an instance of the UI class If the Visualization application had a reference to a BetaUI object instead of a UI object, the visualization would get a different look and feel 23

24 24

25 Making the Example Concrete The screen shot on the next overhead shows the graphical user interface for a Visualization application The application interface supports: – Adding icons representing machines, – Clicking and dragging them around the work area, – Undoing a recent action, like adding a machine 25

26 26

27 The screen shot on the next overhead shows the application with slight changes in the user interface The add and undo button images have been changed from rockets to cherries (cherry bombs) The text under the images has been made italic These changes are accomplished by creating a subclass of UI which has these different characteristics coded into it 27

28 28

29 UI Class Code The UML diagram for the UI class showed these methods: – createButton(), – getFont(), – createPaddedPanel(), – getIcon() 29

30 This is only a subset of the methods the UI class would contain In continuing the example, the book considers these methods: – createButton(), – createButtonOk(), – and createButtonCancel() Code for these methods is given on the following overheads 30

31 public JButton createButton() { JButton button = new JButton(); button.setSize(128, 128); button.setFont(getFont()); button.setVerticalTextPosition(AbstractButton.BOTTOM); button.setHorizontalTextPosition(AbstractButton.CENTER); return button; } 31

32 public JButton createButtonOk() { JButton button = createButton(); button.setIcon(getIcon(“images/rocket-large.gif”)); button.setText(“Ok!”); return button; } 32

33 public JButton createButtonCancel() { JButton button = createButton(); button.setIcon(getIcon(“images/rocket-large-down.gif”)); button.setText(“Cancel!”); return button; } 33

34 The creation of the OK and the Cancel buttons make use of the creation of a simple button The use of the rocket icon/image is hardcoded into the characteristics of the buttons In the visualization application, these button creation methods are used to create visual components 34

35 Take the createButtonCancel() method for example You will notice that it seems to be somewhat like the “undo” button from the GUI, but with different text Shortly we will see how the cancel button code is related to the undo button 35

36 Client Code The constructor for the Visualization client takes an instance of the UI class as a parameter Also, the visualization client has a (protected) instance variable named undoButton of the type JButton 36

37 The following overhead shows code that belongs to the visualization client The client contains a method named undoButton() which returns an instance of a JButton This client method generates a button by making this call on the ui object to one of the factory methods in the UI class: ui.createButtonCancel() 37

38 /* Notice the protected method. This is creepy and disappointing, but not surprising. */ protected JButton undoButton() { if(undoButton == null) { undoButton = ui.createButtonCancel(); undoButton.setText(“Undo”); undoButton.setEnabled(false); undoButton.addActionListener(mediator.undAction()); } return undoButton; } 38

39 ui is the instance variable which refers to the UI object belonging to the client The look and feel of the visualization can be changed by passing the visualization an instance of a different UI when it’s constructed The difference in the createButtonCancel() method would propagate as a difference in the undoButton in the client 39

40 This means the appearance of the visualization client can be changed without making any changes in its code All you have to do is make the new UI class a subclass of the old one You can always pass in a subclass object when the parameter is typed to a superclass 40

41 Code for the BetaUI Subclass BetaUI is the subclass in the example The requirements for BetaUI are these: – The image should be a cherry instead of a rocket – The font should be italic On the next overhead, the constructor for BetaUI is given with some commentary 41

42 public class BetaUI extends UI { public BetaUI() { Font oldFont = getFont(); font = new Font( oldFont.getName(), oldFont.getStyle() | Font.ITALIC, oldFont.getSize()); } /* Notice that the plan is to make use of the superclass as much as possible. In addition to relying on inherited methods, something new is being done here. The font instance variable is inherited in BetaUI. Its value in the subclass depends on the inherited value, but one of its characteristics is being changed. */ 42

43 The rest of the code for BetaUI would be the createButton…() methods The book does this as a challenge As usual, it makes sense to just look at the solution provided, shown on the following overhead The calls to super do most of the work This rest of the code makes the modifications for the new BetaUI 43

44 Solution 17.1 public JButton createButtonOk() { JButton b = super.createButtonOk(); b.setIcon(getIcon(“images/cherry-large.gif”)); return b; } public JButton creatButtonCancel() { Jbutton b = super.createButtonCancel(); b.setIcon(getIcon(“images/cherry-large-down.gif”)); return b; } 44

45 Passing a client an instance of the BetaUI causes it to take on those display characteristics public class ShowBetaVisualization { public static void main(String[] args) { Jpanel panel = new Visualization(new BetaUI()); SwingFacade.launch(panel, “Operational Model”); } 45

46 Shortcomings of the Design The book states that this example illustrates the usefulness of the design pattern However, it also states that the example has some shortcomings The shortcomings will be given on the following overheads After that the book will suggest an alternative design 46

47 One shortcoming as stated in the book: As written, the BetaUI class depends on the ability to override the creation methods – It certainly seems up to this point that this was done intentionally – Based on this observation alone, it’s not clear how this is a shortcoming – It remains to be seen whether or how an alternative would avoid this 47

48 Another shortcoming, as stated in the book: The subclass methods need access to protected instance variables, like font, from the superclass – First of all, I’m not a fan of the protected modifier – Whether you use it or not, you still should have access with get and set methods – It will not be clear exactly what the book means until it presents its alternative 48

49 Challenge 17.2 “Suggest a design change that would still allow for the development of a variety of GUI control factories but that would reduce the reliance of subclasses on method [access] modifiers in the UI class.” 49

50 Comment mode on: I have included the book’s challenge statement because it mentions method modifiers It is worth noting that they are not just concerned with protected instance variables This goes back to the point in the code where they declared a method protected 50

51 Solution 17.2 “One solution for producing a more resilient design would be to specify the expected creation methods and standard GUI properties in an interface, as Figure B.20 shows.” [See the next overhead.] 51

52 52

53 Defining a UI Interface is a Good Idea Comment mode on: I agree that defining an interface is a good idea 53

54 What the Book Code’s Problem Really is, and Whether the Interface Solves Them The real problem with the book’s code is the use of the protected access modifier In the new design the UI class has to implement the interface The implementing class has to implement the methods The implementing class has to provide any needed instance variables 54

55 Interface Methods are Public Interface methods are public by default If protected methods are an issue, this is solved by using the interface The question then becomes, why did you use protected methods to begin with? 55

56 Instance Variables Should Be Private Instance variables provided by an implementing class don’t have a required access modifier It’s the programmer’s choice, package, public, protected, or private Private is the best choice The question then becomes, why did you use protected instance variables to begin with? 56

57 The New Design Still Has Inheritance In the new design, BetaUI is still a subclass of UI It meets the requirements for the interface by inheritance but would not have direct access to inherited private instance variables If BetaUI implemented the interface directly BetaUI would have to provide the instance variables itself 57

58 A better alternative might be to define an abstract class Both NormalUI and BetaUI could extend that class Some things could be implemented in the superclass and inherited Other things could be implemented in the subclasses or overridden 58

59 Abstract Factory and Factory Method The book observes that in a sense an abstract factory class is like a collection of factory methods In the factory method pattern there was a client that used something typed to an interface There was an interface There were classes that implemented the interface 59

60 There was a factory class that contained a factory method That method contained the logic for deciding which kind of object to give the client when it requested one The client called the method and received back a reference to an object that implemented the interface The client didn’t have to know exactly what kind of object was returned to it 60

61 The goal now is to show how the abstract factory pattern functions as a collection of factory methods Each UI class contains a collection, or family, of methods that return objects It’s true that the client doesn’t “know” exactly what kind of object it’s getting back 61

62 For example, it may get back a JButton reference when the object could be an instance of a subclass of JButton On the other hand, there is some choice in what comes back depending on which UI class is used The logic for deciding which UI class to use can be on the client side rather than the service side 62

63 Abstract Factory and Façade Abstract Factory has something in common with the façade pattern It’s like a façade that is restricted to methods that return objects The abstract factory is kind of like a utility Its methods aren’t literally static, but it’s a situation where you are accomplishing something like static methods with a single instance of the UI class 63

64 The Next Examples from the Book The book has several examples and challenges The remaining overheads for this chapter may be in book order in some places In other places, they may be rearranged and the explanations adjusted to try and make things clearer 64

65 As part of the example, the book starts separating classes into different packages Mixed in with the information about abstract factory there is reasoning about what classes belong together and why This is a worthwhile topic It’s a topic that isn’t covered in CSCE 202 65

66 Developing an Abstract Factory Example from the Credit Check Factory Method Example The next example is built on the factory method example of the previous unit Here is a thumbnail review of the factory method example The CreditCheckFactory has a method createCreditCheck() that returns a reference to an object that implements the CreditCheck interface Two classes, CreditCheckOnline and CreditCheckOffline implement the interface 66

67 The code of the createCreditCheck() method knows which kind of object to create based on “server” code conditions Client code will receive a reference to one of the two different kinds of objects Client code doesn’t have to to specify or care which kind of object comes back The UML diagram for this is given on the next overhead 67

68 68

69 Expanding the Example to the Abstract Factory Pattern You may realize that you would like to apply the abstract factory pattern when several related factory methods arise in an application design The idea is that there is a group of related objects that need to be created and you put the methods for creating them together in a common class 69

70 The book now adds things called billing checks and shipping checks to the credit check example It doesn’t really explain what these things are, but it’s apparent that as checks, they are classified with credit checks 70

71 An intermediate UML diagram is given on the next overhead It introduces the idea that you can start putting related things together in packages The diagram is intermediate because it doesn’t have enough information in it to show how it illustrates the abstract factory design pattern Specific comments on that will follow the diagram 71

72 72

73 In the preceding diagram there were two new classes, ShippingCheck and BillingCheck Although they are checks of some sort, they don’t seem to be new types of credit checks They don’t implement the CreditCheck interface 73

74 Not surprisingly then, the CreditCheckFactory doesn’t have a method which constructs objects of these two new classes So the question remains, what are they exactly, and what role will they play in the abstract factory design pattern? 74

75 Another UML diagram is given on the following overhead This is the book’s next step in explaining the design pattern—but it still doesn’t give the whole picture In this diagram, the checks have become interfaces Also, the CreditCheckFactory includes methods that return values that are of the types billing check, shipping check, and credit check 75

76 76

77 Review of the Contents of the Diagram The preceding overhead was a UML diagram of the com.oozinoz.credit package, which contained these elements: – A CreditCheck interface – A CreditCheckOffline class that implements the interface – Two more interfaces, BillingCheck and ShippingCheck – A CreditCheckFactory class containing methods to create instances of each kind of check 77

78 Questions about the Design so Far The diagram is clearly still not complete. Only the CreditCheck interface has an implementing class. There are no classes that implement the BillingCheck or ShippingCheck interfaces The create() methods in the CreditCheckFactory have no classes which they could construct instances of 78

79 Also, there is just the one CreditCheckFactory If there are to be families of methods, then there should be more than one factory class It also turns out that the CreditCheckFactory is now misnamed The factory class has methods for all 3 kinds of checks, not just credit checks 79

80 The issue also remains whether the CreditCheckFactory is a plain concrete class with subclasses Or would it be better to make it an interface or an abstract class 80

81 Bringing the Example to Completion— Adding Packages The book brings the example to completion in more or less the following way: There will be no direct instances of the CreditCheckFactory class in the credit package There will be other packages, one for each country, such as the U.S. or Canada 81

82 In these packages there will be classes that implement the interfaces in the credit package There will also be a factory class which extends the CreditCheckFactory class in the credit package The UML diagram on the following overhead illustrates the relationship between the credit package and the Canada package 82

83 83

84 The Canada package contains live classes BillingCheckCanada, ShippingCheckCanada, and CreditCheckCanadaOnline which implement the check interfaces The package contains the CheckFactoryCanada class which extends the CreditCheckFactory class The contents of the CheckFactoryCanada class aren’t shown in detail in this diagram However, it will either inherit or override the methods which return either a billing check, a shipping check, or a credit check 84

85 Comment mode on: I think the example would be better if the CreditCheckFactory class were abstract I also think it would be better if that class were renamed simply CheckFactory Billing and shipping checks don’t seem to be kinds of credit checks, but methods to create them are included in the factory 85

86 CreditCheckFactory only has the name it does because it was named before the example was expanded Notice that the subclass is named CheckFactoryCanada, not CreditCheckFactoryCanada In other words, implicitly the authors recognize that at the implementation level this is a check factory, not a credit check factory 86

87 Also, if you read the text closely, you’ll discover that at one point the authors refer to the CheckFactoryCanada class as a concrete factory, not an abstract factory This suggests that they recognize that the plain CreditCheckFactory doesn’t have to be a concrete class 87

88 Continuing to Outline the Example No separate package is given for the U.S., but conceptually the example is set up as if there would also be a concrete package for the U.S., analogous to the Canada package There could also be separate packages for other countries, like Mexico, etc. 88

89 The original diagram is shown again on the next overhead. Take a moment to consider what it would look like if a package for the U.S. were added to it 89

90 90

91 If set up as I would set it up, the plain credit package would contain an abstract CheckFactory class and the packages for specific countries would each contain a concrete check factory class that extended it 91

92 There is a reason that the CreditCheckOffline class in the credit package is already a concrete class that implements the CreditCheck interface The CreditCheckOffline is going to be the same for both Canada and the U.S. and can be shared by the code for both That can be taken care of with one implementing class in the parent package The original factory method pattern is still at work because there are two kinds of credit check, online and offline 92

93 The abstract factory pattern is like a collection of factory methods It is after the U.S. package is added to the picture that this becomes apparent createBillingCheck() illustrates the idea There are two kinds of billing check, Canadian and American There are different classes for each, but they both implement the common BillingCheck interface 93

94 createBillingCheck() in the Canada package implementation will return something of type BillingCheck There would also be a createBillingCheck() method in the U.S. package It would also return an object of type BillingCheck This creation method along with the others together form a family of methods for each country 94

95 There could be an additional layer of code on the server side of the example That layer would contain if/else logic to determine whether a customer that a billing check was being run on was Canadian or American 95

96 In other words, there might be a method whatKindOfCustomer() in this example That would be analogous to isAgencyUp() in the factory method example of the previous chapter The actual kind of billing check object returned to a client would depend on the outcome of a call to whatKindOfCustomer() 96

97 The ultimate client code would simply be handed a reference to an object that implemented the BillingCheck interface The client wouldn’t have to be aware or specifically request a billing check for one country or the other Such a solution would make these abstract factory methods quite analogous to plain old factory methods, with the decision about what to return embedded on the server side. 97

98 However, the application overall could also be structured more like the GUI example On the client side would be handed a reference to a customer of a certain nationality, or would itself create one Then what kind of billing check came back would simply be determined by polymorphism when createBillingCheck() was called The server side wouldn’t explicitly be in charge of determining exactly what was returned 98

99 The Implementation of the CheckFactoryCanada Class I’m skipping this and everything else in the book up until its comments on packages. Enough is enough… 99

100 Packages and Abstract Factories The book now returns to the question of packages What more they actually have to say about packages is contained in the next challenge 100

101 Challenge 17.5 Write down an argument supporting the decision to place each factory and its related classes in a separate package. Or, argue that another approach is superior. 101

102 Solution 17.5 An example justification is: Placing country-specific classes in separate packages helps our Oozinoz developers to organize our software and our development efforts. By placing the classes for each country in a separate package, we keep country-specific packages independent of one another. 102

103 We can be confident, for example, that U.S.- specific classes have no impact on Canada- specific classes. We can also easily add support for new countries. For example, when we start doing business with Mexico, we can create a new package that provides the check services we need in a way that makes sense in that country. 103

104 This has the further advantage of letting us assign the credit.mx package to a developer who has expertise in working with services and data from Mexico. 104

105 An argument against: Although this separation is nice in theory, it’s overwrought in practice. I’d rather have only one package with all the classes in it, at least until we expand to nine or ten countries. Spreading these classes over multiple packages winds up causing me three or more times the configuration-management work when I need to implement a change that cuts across all these packages. 105

106 Comment mode on: Eventually, as software grows, you may start to use packages If so, you’ll have to decide how to divide them up. When the time comes, you’ll have to make your own decision about the right approach 106

107 The book’s argument “against” summarizes my feelings about packages at this stage Up through CSCE 202 and CSCE 302 there are no programming projects so complex that using packages is justified Trying to use them just introduces an artificial level of complexity Why, for example, Eclipse generates packages for a simple program consisting of a couple of classes is beyond me… 107

108 Another Example The “other” example for the Abstract Factory design pattern builds on the “other” example for the Factory Method design pattern. Because this set of overheads is already so long, no code will be given. Screen shots will be given, along with a UML diagram. 108

109 On the following overhead is the initial dialog box for the application. The client is allowed to choose what interface is wanted—i.e., what family of classes is desired, the fruit classes or the mushroom classes. After that two overheads are shown, one for each of the two interfaces. 109

110 110

111 111

112 112

113 UML for the Pattern Although not really complete, the book’s last diagram is repeated on the following overhead. What’s missing is some indication that the factory makes use of the check classes What’s also missing is another set of classes representing another family, for example, a set of classes for the United States, Mexico, etc. 113

114 114

115 UML for the Other Example On the following overhead I show a subset of the UML diagram for the fruit and mushroom example. This is an attempt to show factories that are responsible for creating families of fruits and mushrooms. 115

116 116

117 Lasater’s UML Diagram Lasater’s diagram closely follows my diagram in structure, reinforcing the idea that that is a reasonable way to view the pattern He does use an abstract class for the abstract factory, which may be a plus He also uses generic names that aren’t tied to a specific example. 117

118 118

119 Summary What follows is a fairly faithful summary of what the book includes in the summary, interspersed with commentary The Abstract Factory pattern lets you arrange for a client to create objects that are part of a family of related dependent objects Comment mode on: It is clear from the examples that the objects are related The book hasn’t explained specifically what it means when it now says that they’re dependent 119

120 One example of related objects is groups of objects for different GUIs Another example of related objects is groups of objects for different countries 120

121 As with Factory Method, Abstract Factory isolates clients from knowing which class to instantiate. Comment mode on: This can be true, but the examples in this chapter didn’t grow to the point of illustrating it specifically For example, there was no server side code that checked which country a check request was being made for 121

122 Comment mode, continued: Going back to the earlier example there was just one example of using an abstract factory It contained this call: JPanel panel = new Visualization(new BetaUI()); Whatever else you might say, it’s clear that this code had to specify which UI to use The only question is whether code of this form would appear on the client side or on the server side of the application overall 122

123 Comment mode, continued: No example client code was given for the Canadian credit check example However, the situation is analogous to the previous one At some point a CheckFactoryCanada object would have to be created so that the unique implementations of the methods in it could be called The question is whether the creation of the object would be in client code or in server code 123

124 The End 124

125 125


Download ppt "Chapter 17 Abstract Factory Summary prepared by Kirk Scott 1."

Similar presentations


Ads by Google