Friday, June 29, 2012

Design Patterns Explained - Review Questions and Answers


Table of Contents

  • Chapter 1: The Object-Oriented Paradigm
  • Chapter 2: The UML - The Unified Modeling Language
  • Chapter 3: A Problem That Cries Out for Flexible Code
  • Chapter 4: A Standard Object-Oriented Solution
  • Chapter 5: An Introduction to Design Patterns
  • Chapter 6: The Façade Pattern
  • Chapter 7: The Adapter Pattern
  • Chapter 8: Expanding Our Horizons
  • Chapter 9: The Strategy Pattern
  • Chapter 10: The Bridge Pattern
  • Chapter 11: The Abstract Factory Pattern
  • Chapter 12: How Do Experts Design?
  • Chapter 13: Solving The CAD/CAM Problem with Patterns
  • Chapter 14: The Principles and Strategies of Design Patterns
  • Chapter 15: Commonality and Variability Analysis (CVA)
  • Chapter 16: The Analysis Matrix
  • Chapter 17: The Decorator Pattern
  • Chapter 18: The Observer Pattern
  • Chapter 19: The Template Method Pattern
  • Chapter 20: Lessons from Design Patterns: Factories
  • Chapter 21: The Singleton Pattern and the Double-Checked Locking Pattern
  • Chapter 22: The Object Pool Pattern
  • Chapter 23: The Factory Method Pattern
  • Chapter 24: Summary of Factories (no review questions)
  • Chapter 25: Design Patterns Reviewed: A Summation and a Beginning

Chapter 1: The Object-Oriented Paradigm

Observations

1. Describe the basic approach used in functional decomposition.
Functional decomposition is the approach to analysis that breaks down (decomposes) a problem into its functional parts without too much concern for global requirements and future modifications.
2. What are three reasons that cause requirements to change?
The user's understanding of what they need and what is possible grows and changes as they discuss the problem with analysts. The developer's understanding of what is possible and what is needed evolves as they become familiar with the domain and with the software. The technical environment evolves, forcing changes in how to implement.
3. I advocate thinking about responsibilities rather than functions. What is meant by this? Give an example.
Rather than thinking first about how something is done (functions), the analyst should focus on what the routine is responsible for doing - how it does it does not matter. The control program is much simpler in this case.
4. Define "coupling" and "cohesion". What is "tight" coupling?
Cohesion is how strongly the internal operations of a routine are related to each other. Coupling is how strongly a routine is dependent upon other routines.
5. What is the purpose of an "interface" to an object?
It provides the methods whereby other objects can tell the object what to do.
6. Define instance of a class.
A specific, unique occurrence of a more abstract object. An object is an instance of a class.
7. A class is a complete definition of the behavior of an object. What three aspects of an object does it describe?
The three elements of a class are: the data elements, the methods, the interfaces (ways that data and methods can be accessed).
8. What does an abstract class do?
At the conceptual level, an abstract class is a placeholder for a set of classes. It gives a way to assign a name or label to a set of classes. At the specification level, an abstract class is a class that does not get instantiated.
9. What are the three main types of accessibility that objects can have?
Public, Protected, Private
10. Define encapsulation. Give one example of encapsulation of behavior.
Any kind of hiding. Both data and behavior may be encapsulated.
11. Define polymorphism. Give one example of polymorphism.
The ability to refer to different derivations of a class in the same way.
12. What are the three perspectives for looking at objects?
Conceptual: the high-level concepts in a system (concepts, not software). At the conceptual level, an object is a set of responsibilities.
Specification: the interfaces between things in the software (software, not code). At the specification level, an object is a set of methods.
Implementation: how an individual routine works (code). At the implementation level, an object is code and data.

Interpretations

13. Sometimes, programmers use "modules" to isolate portions of code. Is this an effective way to deal with changes in requirements? Why or why not?
Changes to one function or routine can have impacts on other routines. Usually, routines are not independent .
14. It is too limited to define an abstract class as a class that does not get instantiated. Why is this definition too limited? What is a better (or at least alternative) way to think about abstract classes?
It is too limited because it only talks in terms of its implementation: what the abstract class does and how it is treated as software. It does not describe why I would want to use an abstract class: the motivation for it and how to think about it. It ignores the "conceptual perspective" of objects that analysts need to keep in mind as they work with users to understand problems. At the conceptual level, an abstract class is a placeholder for a set of classes. It gives a way to assign a name or label to a set of classes so that I can interact with them as a whole without getting trapped by the details.
15. How does encapsulation of behavior help to limit the impact of changes in requirements? How does it save programmers from unintended side effects?
It makes the control program much less complicated since it does not have to be responsible for as much. It limits the impact that changes to the internals of an object can have on the rest of the application.
16. How do interfaces help to protect objects from changes that are made to other objects?
Interfaces define the only ways that those external objects can communicate with the object. It protects me from side effects because I know what is coming into the system.
17. A classroom is used to describe objects in a system. Describe this classroom from the conceptual perspective.
The classroom contains students who are responsible for their own behaviors: how to move from here to there, how to go from class to class. It contains a teacher who tells students where to go.

Opinions and Applications

1. Changing requirements is one of the greatest challenges faced by systems developers. Give one example from your own experience where this has been true.
2. There is a fundamental weakness in functional decomposition when it comes to changes in requirements. Do you agree? Why or why not?
3. What do you think is the best way to deal with changing requirements?


Chapter 2: The UML - The Unified Modeling Language

Observations

1. What is the difference between an "is-a" relationship and a "has-a" relationship? What are the two types of "association" relationships?
"is-a" indicates that one object is a "kind of" a class; for example, a "sail boat" is a kind of "boat" which is a kind of "type of transportation".
"has-a" indicates that one class "contains" another class; for example, a car has wheels.
There are two types of "associations": containment (has-a) and "uses"
2. In the Class diagram, a class is shown as a box, which can have up to three parts. Describe these three parts.
The  box is the name (label) of the class. This is required.
The middle box, if it is shown, shows the data members of the class.
The bottom box, if it is shown, shows the methods (functions) of the class.
3. Define cardinality.
Cardinality indicates the number of things that another object can have
4. What is the purpose of a Sequence diagram?
The Sequence diagram is one type of Interaction Diagram in the UML. It shows how objects interact with other objects.

Interpretations

1. Give an example of an "is-a" relationship and the two "association" relationships. Using these examples,
Draw them in a Class diagram
Show cardinality on this Class diagram
Is-a example: "Sailboat" is-a "boat"
Has-a example: Sailboat has-a sail (one to many)
Uses example: A marina contains one or more Sailboats
2. Figure 2-8 shows a Sequence diagram. How many steps are shown in the figure? How many objects are shown and what are they?
There are 13 steps in the diagram
There are 6 objects shown: Main, ShapeDB, Collection, shape1:Square, shape2:Circle, and Display.
3. When objects communicate with each other, why is it more appropriate to talk about "sending a message" than "invoking an operation"?
When objects "talk" to each other, it is called "sending a message." You are sending a request to another object to do something rather than telling the other object what to do. You allow the other object to be responsible enough to figure out what to do. Transferring responsibility is a fundamental principle of object-oriented programming. It is quite different from procedural programming where you retain control of what to do next, and thus might "calling a method" or "invoke an operation" in another object.

Opinions and Applications

1. How many steps should be shown on a Sequence diagram?
As many as it takes to communicate clearly, and no more


Chapter 3: A Problem That Cries Out for Flexible Code

Observations

1. What five features in sheet metal will this system have to address?
The features are Slot, Hole, Cutout, Special, and Irregular
2. What is the difference between the V1 system and the V2 system?
The V1 system has a collection of subroutine libraries that interacts with the CAD/CAM model. To get information about the CAD/CAM model, you have to make a series of calls
The V2 system is an object-oriented system. The geometry is stored in objects, each of which represents a feature. To get information about a feature, you interrogate the object for that feature.

Interpretations

1. What is the essential challenge of the CAD/CAM problem?
We have different types of CAD/CAM systems. A third system (the "expert system") has to extract information from whichever CAD/CAM system in order to work with the geometry. The two CAD/CAM systems are implemented in completely different ways and require completely different ways of interacting with them, even though they contain essentially the same information
2. Why is polymorphism needed at the geometry-extractor level but not at the feature level?
Polymorphism is required at the geometry extractor level because the "expert system" needs to know what type of features it is dealing with: slot, hole, etc. It is insufficient for the expert system simply to work on generic "features." Polymorphism does not buy me anything at the feature level. The expert system does not need to care about the particular method that is used to extract that feature. While we could hard-code the extraction method into the expert system, that would be bad if we ended up getting a new CAD/CAM system that uses yet another method of working with geometry. Polymorphism frees us from having to worry about the particular extraction method: the expert system can simply use a generic "geometry extractor" that worries about extractions.

Opinions and Applications

1. I spend time defining terms related to the CAD/CAM problem.
Why did I do this?
Did you find this useful or a distraction?
Is it important to understand the user's terminology?
What is the most effective method you have found for recording user terminology?


Chapter 4: A Standard Object-Oriented Solution

Observations

1. Identify each of the elements of the UML diagram in Figure 4-3.
Abstract class
Cardinality
Derivation
Composition
Public methods
Abstract class: Feature (in italics)
Cardinality: A Model can have no Features, 1 Feature, or many Features.
Derivation: SlotFeature, a HoleFeature, a CutoutFeature, an IrregularFeature, or a SpecialFeature all derive from Feature. They are all "kinds of" Features.
Composition: A Model is composed of Features
Public method: Geerations is a public method of the CutoutFeature.
2. What is the essential ability required by the CAD/CAM application?
They need the ability to plug-and-play different CAD/CAM systems without changing the expert system (p. 63)
3. The first solution exhibits four problems. What are they?
There is redundancy amongst the methods It is messy
It has tight coupling: features are related to each other
It has low cohesion: core functions are scattered amongst many classes.

Interpretations

1. Describe the first approach to solving the CAD/CAM problem. Was it a reasonable first approach?
The first object-oriented approach to a solution is to specialize a feature for each case: a Slot class for V1 and a Slot class for V2. Each V1 type case communicates with the V1 libraries and V2 type case communicates with V2 libraries. It is a reasonable approach to begin with (p. 59). It gives insights into the problem. But it should not be implemented!

Opinions and Applications

1. "Delay as long as possible before committing to the details." Do you agree? Why or why not?
2. One solution was rejected because "intuition told me it was not a good solution." Is it appropriate for analysts / programmers to be guided by their instincts?


Chapter 5: An Introduction to Design Patterns

Observations

1. Who is credited with the idea for design patterns?
The architect, Chrisher Alexander developed design patterns in the late 1970s. The "Gang of Four" took this idea in the 1990s and applied them to software design. I point out that one school of anthropology used patterns to study cultures in the 1940s. Also, the ESPRIT consortium used patterns for understanding human thought patterns in ways that could be implemented in computer programs in the 1980s
2. Alexander discovered that by looking at structures that solve similar problems, he could discern what? Designs / solutions that are high quality. And that this was objectively measurable
3. Define pattern. A pattern is a solution to a problem that occurs in a given context.
4. What are the key elements in the description of a design pattern?
To be complete, a pattern description must have the following eight elements:
  • Name: a label that identifies it
  • Intent: a description of the purpose of the pattern
  • Problem: a description of the problem being solved
  • Solution: what the solution is in the given context
  • Participants / Collaborators: the entities involved in the solution
  • Consequences: what happens as a result of using the pattern. What forces are at work.
  • Implementation: how to implement the pattern in one or more concrete ways.
  • GoF Reference: where to look in the Gang of Four book for more information.
5. What are three reasons for studying design patterns?
Patterns make it possible to reuse solutions
Patterns help with communication between analysts, giving a shorthand terminology.
Patterns give you perspective on the problem, freeing you from committing to a solution too early.
6. The Gang of Four suggests a few strategies for creating good object-oriented designs. What are they?
Design to interfaces
Favor aggregation over inheritance Find what varies and encapsulate it  

Interpretations

1. "Familiarity sometimes keeps us from seeing the obvious." In what ways can patterns help avoid this? We can gain insights from previous solutions, have our attention drawn to features of the problem that I might not otherwise think of (until too late)
2. The Gang of Four cataloged 23 patterns. Where did these patterns come from? It came from their insights into solutions that had already been developed within the software community.
3. What is the relationship between "consequence" and "forces" in a pattern? Consequences are the cause-and-effect of using the pattern Forces are the factors at play in a particular problem that constrain and shape the possible solutions.
4. What do you think "find what varies and encapsulate it" means? Look for what is changing and make a more generic version of it so that you can see what is truly going on in your system and not get caught up in the details.
5. Why is it desirable to avoid large inheritance hierarchies? They are very complex to understand and to maintain.

Opinions and Applications

1. Think of a building or structure that felt particularly "dead". What does it not have in common with similar structures that seem to be more "alive"?
2. "The real power of patterns is the ability to raise your level of thinking." Have you had an experience in which this was true? Give an example.


Chapter 6: The Façade Pattern

Observations

1. Define Façade.
A Façade is "The face of a building, especially the principal face" - dictionary.com. It is the front that separates the street from the inside.
2. What is the intent of the Façade pattern?
Provide a unified interface to a set of interfaces in a sub-system
3. What are the consequences of the Façade pattern? Give an example.
The Façade simplifies the use of the required subsystem. However, since the Façade is not complete, certain functionality may be unavailable to the client. Example is a reporting application that needs a routine way to access on certain portions of a database system: The Façade would provide an interface to those portions and not the entire API of the database.
4. In the Façade pattern, how do clients work with subsystems?
Clients work with sub-systems through the Façade's interfaces. They do not interact with the underlying methods directly
5. Does the Façade pattern usually give you access to the entire system?
Not usually. In general, Façade give access to a portion of the system, one that is customized to our needs.

Interpretations

1. The Gang of Four says that the intent of the Façade pattern is to "provide a unified interface to a set of interfaces in a sub-system. Façade defines a higher-level interface that makes the subsystem easier to use." What does this mean? Give an example.
The Façade gives a simpler way to access an existing system by giving an interface that is customized to the needs you have.
Example is a class that insulates a client program from a database system
2. Here is an example of a Facade that comes from outside of software. Pumps at gasoline stations in the US can be very complex. There are many options on them: how to pay, the type of gas to use, watch an advertisement. One way to get a unified interface to the gas pump is to use a human gas attendant. Some states even require this.
  • What is another example from real life that illustrates a Facade?
  • Another example could be a stockbroker who serves as the interface to a complex system of stock trades.

Opinions and Applications

1. If you need to add functionality beyond what the system provides, can you still use the Façade pattern?
2. What is a reason for encapsulating an entire system using the Façade pattern?
3. Is there a case for writing a new system rather than encapsulating the old system with Façade? What is it?
4. Why do you think the Gang of Four call this pattern "Façade"? Is it an appropriate name for what it is doing? Why or why not?


Chapter 7: The Adapter Pattern

Observations

1. Define Adapter.
"Adapter" is something that allows one thing to modify itself to conform to the needs of another thing.
2. What is the intent of the Adapter pattern?
The intent of the Adapter is to match an existing object that is beyond your control to a particular interface.
3. What are the consequences of the Adapter pattern? Give an example.
A consequence is that the pattern allows for preexisting objects to fit into new class structures without being limited by their interfaces (p. 102). The example in the book is the drawing program that wants to use an existing Circle object but the existing object doesn't provide exactly the same methods as the rest of the system. The Adapter provides a translation to these methods.
4. Which object-oriented concept is being used to define the relationship between Shape and Points, Lines, and Squares?
Polymorphism
5. What is the most common use for the Adapter pattern?
To allow for continued use of polymorphism. It is often used in conjunction with other design patterns.
6. What does the Adapter pattern free you from worrying about?
Adapter frees me from worrying about the interfaces of existing classes when doing a design. If the class doesn't do what I need, I can create an Adapter to give it the correct interface.
7. What are the two variations of the Adapter pattern?
Object Adapter: relies on one object to contain the other object.
Class Adapter: uses multiple inheritance to provide the interface

Interpretations

1. The Gang of Four says that the intent of the Adapter pattern is to "convert the interface of a class into another interface that the clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces."
  • What does this mean?
  • Give an example.
It means that I have a class that needs to interact with another class through a certain set of method calls. If the interface of that other class does not provide these method calls, the Adapter sets up a new interface to do the translation. An example would be a reporting application that needs pulls data from two different database systems. My application wants to use a "GetDate" method to pull information from the database, but the database systems don't provide that through their API. I write an Adapter that provides the GetDate method in its interface and is responsible for pulling the data appropriately.
2. "The Circle object wraps the XXCircle object." What does this mean?
Circle completely insulates XXCircle from the system. Circle manifests the entire behavior of XXCircle to the system, although with a different interface / way of accessing XXCircle.  
3. The Façade pattern and the Adapter pattern may seem similar. What is the essential difference between the two?
In both cases, there is a preexisting class or classes that have functionality I need. In both cases, I create an intermediary object with interfaces that my system wants to use and that has responsibility for mapping that to the preexisting class. Both Façade and Adapter are wrappers.
The Adapter is used when the client already has predefined interfaces that it expects to use and when I need to use polymorphism.
The Façade is used when I need a simpler interface to the existing object.
4. Here is an example of an Adapter that comes from outside of software. A translator at the UN lets diplomats from different countries reason about and argue for the positions of their own countries in their own languages. The translator makes "dynamically equivalent" representations from one language to the other so that the concepts are communicated in the way that the recipient expects and needs to hear it.
What is another example from real life that illustrates an Adapter?
Another example could be a travel agent, seen as the common interface between a passenger making arrangements and an airline with its own systems. Each has competing systems, speaking different languages

Opinions and Applications

1. When is it more appropriate to use the Façade pattern rather than the Adapter pattern? How about the Adapter pattern instead of Façade pattern?
2. Why do you think the Gang of Four call this pattern Adapter? Is it an appropriate name for what it is doing? Why or why not?


Chapter 8: Expanding Our Horizons

Observations

1. What do I say is the right way to think about encapsulation?
Encapsulation is best thought of as "any kind of hiding." This can mean hiding data, or behavior, or implementations, or derived classes, or any other thing.
2. What are the three perspectives for looking at a problem? (You may need to review Chapter 1, "The Object-Oriented Paradigm").
The three perspectives are the Conceptual perspective, the Specification perspective, and the Implementation perspective.

Interpretations

1. There are two mention different ways to understand objects: "data with methods" and "things with responsibilities."
  • In what ways is the second approach superior to the first?
  • What additional insights does it provide?
The second approach takes looks at what an object is supposed to do, what its essential concepts are, without worrying about how to do them. It fights against the tendency of programmers to want to jump to coding too soon.
By focusing on what an object is supposed to do rather than how it does it, I can be more flexible in design. It helps to think about the public interfaces that will be required and what those interfaces need to do.
2. Can an object contain another object? Is this different than one object containing a data member?
In object-oriented systems, everything is an object. An object can contain another object, data, or anything. In fact, data types are also objects, so there is no difference.
3. What is meant by the phrase find what varies and encapsulate it? Give an example
Variation represents special cases that complicate understanding. At the conceptual level, find a common label to a set of these variations. Variation can be in data, in behavior
4. Explain the relationship between commonality/variability analysis and the three perspectives of looking at a problem.
By looking at what objects must do (the Conceptual perspective), we determine how to call them (the Specification perspective). Commonality / Variability analysis reveals the interfaces I need to handle all of the cases of the concept.
Specifications become abstract classes at the implementation level . Given a specification, the Implementation perspective shows how each of its variations must handled. 
5. An abstract class maps to the "central binding concept." What does this mean?
The core concept is what defines what is common across a set of things that vary. An abstract class represents this core concept. The name you give to that core concept Is the name for the abstract class.
6. "Variability analysis reveals how family members vary. Variability only makes sense within a given commonality."
  • What does this mean?
  • What types of objects are used to represent the common concepts?
  • What types of objects are used to represent the variations?
Variability analysis looks for all of the variants of a concept: all of the concrete instances of an abstract class. The "commonality" labels the essential concept that ties the variations together. The goal is to find the best unifying name for the set of variations so that you can have a handle to work with them as a set: to work with the forest instead of the trees.
Abstract classes are used to represent the common concept. Concrete instances are used to represent the variations.

Opinions and Applications

1. Why is it better to start out focusing on motivations rather than on implementation? Give an example where this has helped you.
2. Preconceived notions limit one's ability to understand concepts. This was shown to be the case with encapsulation. Can you think of a situation in which your preconceived notions got in the way of understanding requirements? What happened and how did you overcome it?
3. The term inheritance is used both when a class derives from an nonabstract class to make a specialized version of it and when an abstract class is used as a starting point for different implementations. Would it be better if we had two different terms for these concepts instead of using the same term?
4. How might you use commonality/variability analysis to help you think about ways to modify a system?
5. It is important to explore for variations early and often.
  • Do you believe this? Why or why not?
  • How does it help to avoid pitfalls?
6. Commonality/variability analysis is an important primary tool for identifying objects, better than "looking for the nouns." Do you agree? Why or why not?
7. This chapter tried to present a new perspective on objects? Did it succeed? Why or why not?


Chapter 9: The Strategy Pattern

Observations

1. What are some alternatives for handling new requirements?
Cut and paste
Switches or ifs on a variable specifying the case we have Using function pointers or delegates (a different one representing each case) Inheritance (make a derived class that does it the new way) Design patterns
2. What are the three fundamental principles proposed by the Gang of Four that guide how to anticipate change?
"Program to an interface, not an implementation." 1
"Favor object aggregation over class inheritance." 2 "Consider what should be variable in your design.
3. What is the intent of the Strategy pattern?
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it
4. What are the consequences of the Strategy pattern?
The Strategy pattern defines a family of algorithms.
Switches and/or conditionals can be eliminated. You must invoke all algorithms in the same way (they must all have the same interface).

Interpretations

1. The Gang of Four suggests "considering what should be variable in your design." How is this different from focusing on the cause of redesign?
The focus is on seeing where change might occur and then encapsulating it so that your system will not be affected by change when it occurs. It assumes you will not be able to anticipate what will change.
2. What is wrong with copy-and-paste?
duplications of code result in higher maintenance costs
3. What is "switch creep"?
The flow of the switches themselves becomes confusing. Hard to read. Hard to decipher. When a new case comes in, the programmer must find every place it can be involved (often finding all but one of them). I like to call this "switch creep".
4. What are the advantages of the design patterns approach to handing variation?
Improves cohesion
Aids flexibility Makes it easier to shift responsibility Aids understandability
5. Why is the object-aggregation approach to inheritance superior to direct class inheritance for handling variation?
But this simplifies the bigger, more complicated program. Second, by doing this, I have made inheritance better. When I need to use inheritance, there is now only one piece of functionality changing within any one class. The bottomline is, the approach espoused by patterns will scale while the original use of inheritance will not.

Opinions and Applications

1. Have you ever been in a situation where you did not feel you could afford to anticipate change? What drove you that way? What was the result?
2. Should you ever use switch statements? Why or why not?


Chapter 10: The Bridge Pattern

Observations

1. Define decouple and abstraction.
Decouple means to separate or detach one thing from another. In our context, it means to have one thing behave independently from another (or at least to state explicitly what that relationship is)
Abstraction means to generalize or conceptualize: to step back from the more concrete to the more conceptual or abstract.
2. How is implementation defined in the context of the Bridge pattern?
Implementation refers to the objects that the abstract class and its derivations use to put themselves into operation or into service.
3. What are the basic elements of a sequence diagram?
The basic elements are:
  • Boxes. These are shown at the  and represent the objects that are interacting.
  • Name in the form objectname:classname. The object name is optional.
  • Dashed vertical lines, also known as swim lanes, one for each object, to indicate time.
  • Arrows, may be horizontal or vertical, showing the interaction between objects. Each arrow is labeled to describe the interaction
  • Notes. This is optional.
4. What is Alexander's view of how to use patterns? Does he advocate starting with the solution first or the problem to be solved first?
Alexander says that a pattern describes a problem which occurs over and over again in the environment and then describes the core of the solution to that problem. This means that it is most important to understand the problem first and then tackle the solution. It is a mistake to try finding the solution first.
5. What does commonality analysis seek to identify? What does variability analysis seek to identify?
Commonality analysis focuses on finding structures that will not change over time while variability analysis looks for structures that are likely to change.
6. What is the basic problem being solved by the Bridge pattern?
The derivations of an abstract class must use multiple implementations without causing an explosion in the number of classes
7. Define the "one rule, one place" strategy.
"one rule, one place" says you should implement a rule in only one place. (p. 144). Note that this results in a greater number of smaller methods.
8. What are the consequences of the Bridge pattern?
Decoupling of the implementations from the objects that use them increases extensibility. Client objects are freed from being aware of implementation issues.  

Interpretations

1. The Gang of Four says that the intent of the Bridge pattern is to "decouple an abstraction from its implementation so that the two can vary independently." What does this mean? Give an example.
What it means is that you can have an abstraction that is independent of its implementations. (p. 150) An example is a shape object that is responsible for knowing shapes and a Drawing class that is responsible implementing drawing routines. Individual shapes don't have to know how to do drawings
2. Why can tight coupling lead to an explosion in the number of classes?
Tight coupling means that as you get more variations in implementation, each class has to be responsible for its own implementation.

Opinions and Applications

1. "Look at objects in terms of their responsibilities rather than their behaviors." How does this affect your view of the use of inheritance in an object-oriented system?
2. Why do you think the Gang of Four call this pattern "Bridge"? Is it an appropriate name for what it is doing? Why or why not?


Chapter 11: The Abstract Factory Pattern

Observations

1. While using "switches" can be a reasonable solution to a problem that requires choosing among alternatives, it caused problems for the driver problem discussed in this chapter. What were these problems? What might a switch indicate the need for? The rules for determining which driver to use are intermixed with the actual use of the drivers. This creates both tight coupling and strong cohesion.
Switches may indicate a need for abstraction
2. Why is this pattern called "Abstract Factory"?
At first glance, you might be tempted to conclude it is because the factory is implemented as an abstract class with a derivation for each case. But that is not the case. This pattern is called the "Abstract Factory" because the things it is intended to build are themselves defined by abstractions. How you choose to implement the factory variations is not specific to the pattern.
3. What are the three key strategies in the Abstract Factory?
Find what varies and encapsulate it
Favor aggregation over inheritance
Design to interfaces, not to implementations
4. In this pattern, there are two kinds of factories. What does the "Abstract Factory" class do? What do the "concrete factory" classes do?
The "Abstract Factory" class specifies which objects can be instantiated by defining a method for each type of object.
The "concrete factory" classes specify which objects are to be instantiated.
5. What are the consequences of the Abstract Factory pattern?
The Abstract Factory isolates the rules about which objects to use from the logic about how to use these objects.

Interpretations

1. The Gang of Four says that the intent of the Abstract Factory pattern is to "provide an interface for creating families of related or dependent objects without specifying their concrete classes." What does this mean? Give an example.
It means that I need to coordinate the instantiation of several objects, a family of objects. However, I want to insulate my system from having to know specifics of the particular concrete object being instantiated. That is, the selection of which particular concrete instance to use might depend upon another factor. An example would be a system that wants to manage records in a database but be insulated from the specifics of which DBMS is being used.

Opinions and Applications

1. Why do you think the Gang of Four call this pattern "Abstract Factory"? Is it an appropriate name for what it is doing? Why or why not?
2. How do you know when to use the Abstract Factory pattern?

Chapter 12: How Do Experts Design?

Observations

1. Alexander uses the term, "alive" to characterize good designs. What terms do I suggest using when it comes to software?
"When you read ‘alive', think ‘robust' and ‘flexible' systems
2. Good design requires keeping what in mind?
Keeping the big picture in mind. Being able to consider the forest first and then the trees. (p. 189)
3. Alexander suggests that the best approach to design involves"complexification." What does this mean?
Complexification is the approach to design to starts by looking at the problem in its simplest terms and then adds additional features (distinctions), making the deisgn more complex as we go because we are adding information
4. To Alexander, what relationships does a pattern define?
A pattern defines relationships between the entities in his problem domain (p. 191, 192) This is why define a pattern as a solution to a problem in a context. The entities describe the context in which the pattern exists.
5. What are Alexander's five steps to design?
Identify patterns that are present in your problem.
Start with context patterns (those that create context for other patterns)
Work inward from the context
Refine the design
Implement

Interpretations

1. I quote Alexander, "But it is impossible to form anything which has the character of nature by adding preformed parts." What does Alexander mean by this?
Alexander believes that designs that have the "character of nature" are those that humans would judge has being superior in design. They are "alive" and feel right. He believes that buildings (or in our case, software) that is built simply by assembling stock parts will not feel "alive". They will have all the charm of 60s style block houses: functional but dead. In software terms, it works the same way: cobbling together objects does not create solutions that are easily maintained: robust and flexible.

Opinions and Applications

1. Sometimes, the case that is made for object-oriented programming is that it gives you small, reusable components that you can assemble to create a program. Does this align with Alexander or contradict him? Or is Alexander speaking at a different level? Why?
2. Have you ever seen a courtyard or entryway in a house or building that has felt particularly "dead" or uninviting? As you look at Alexander's description of the Courtyard pattern, what entities did your courtyard fail to resolve or involve?
3. Think of one software project in which you think Alexander's approach would apply or an approach in which it would not apply. What are the issues? Keep this case in mind as you read the rest of the book.


Chapter 13: Solving The CAD/CAM Problem with Patterns

Observations

1. What are the three steps to software design with patterns that I use?
Find the patterns in the problem domain
For the set of patterns to be analyzed, pick the pattern that provides the most context and apply it to the conceptual design. Identify additional patterns that are now suggested. Repeat.
Add detail to the conceptual design. Expand the method and class definitions.
2. Define "context."
One definition is "the interrelated conditions in which something exists or occurs. An environment or a setting." (p. 201)
3. What do I mean by "seniormost" pattern?
The seniormost pattern is the pattern that creates the context for the other patterns. When it comes to applying patterns to a design, we want start with the "seniormost" patterns first and then work down (p. 203)
4. When comparing two patterns, I suggest two rules for discerning which pattern might be seniormost. What are these rules? Does one pattern define how the other pattern behaves?
Are the two patterns interrelated? Mutually dependent?
5. Define "canonical form" of a pattern. When is it used?
The canonical form of a pattern is it standardized, simplified representation. This is generally what is shown in the Gang of Four book and is shown in each of the pattern descriptions in Design Patterns Explained. I suggest starting with the canonical form and then mapping classes and elements of the problem into it.

Interpretations

1. Do I believe that your entire problem can always be defined in terms of patterns? If not, what else is needed?
The answer is "not always." Generally, patterns give you a way to get started with understanding the problem. However, analysis remains a human activity! (which is good because we still have jobs!). it is usually the case that the analyst ends up having to identify relationships amongst concepts in the problem domain. One good approach to this is Commonality / Variability analysis, which has been discussed before.
2. In the CAD/CAM problem, I reject the Abstract Factory as the "seniormost" pattern. What reasons do they give?
The Abstract Factory requires knowing what classes will be defined. These are defined by other patterns. Therefore, Abstract Factory depends upon other patterns; they create the context for the Abstract Factory. Therefore, it is not seniormost
3. In the CAD/CAM problem, what reason(s) do I give for labeling Bridge as senior to Adapter?
Clearly, there is a relationship between Bridge and Adapter. But Adapter's interfaces cannot be determined without Bridge. Without the Bridge, Adapter's interfaces simply don't exist. Since Adapter depends upon Bridge and not vice-versa, Bridge is more senior (p. 204)

Opinions and Applications

1. Once all of the patterns are applied, there are still likely to be more details. I assert that Alexander's general rules (design by starting with the context) still apply. Does this ever s? Is there ever a time when you should go ahead and dive into the details? Isn't that what "rapid prototyping" suggests? How can you avoid this temptation that all programmers have? Should you?

Chapter 14: The Principles and Strategies of Design Patterns

Observations

1. When it comes to choosing how to implement a design, what question do I suggest asking?
Rather than ask, "Which implementation is better?" ask, for each alternative, "Under what circumstances would this alternative be better than the other alternative" and then "Which of these circumstances to I have in my problem domain?"
2. What are the five errors of using design patterns?
Superficiality, Bias, Selection, Misdiagnosis, Fit

Interpretations

1. The "open-closed" principle says, "modules, methods, and classes should be open for extension while closed for modification." What does this mean?
Bertrand Meyer puts this forward as a way to minimize risk when changing systems. Basically, it means that we want to be able to extend the capabilities of our systems without substantially changing it. Design in such a way that the software can absorb new variations without having to introduce new fundamental structure (p. 218).
2. In what way does the Bridge pattern illustrate the open-closed principle?
Bridge allows us to add new implementations without changing any existing classes

Opinions and Applications

1. I suggest that even though a design pattern might give you insights into what could happen, you do not have to build your code to handle those possibilities. How do you decide which possibilities to handle now and which to be ready for in the future?
2. Give a concrete example of the danger of misapplying a design pattern, based upon your current work.

Chapter 15: Commonality and Variability Analysis (CVA)

Observations

1. I suggest two approaches to identifying commonalities and variabilities. What are they?
Pick any two items in the problem domain and ask, "is one of these a variation of the other" and "are both of these a variation of something else".
Look at the problem and identify the major concepts.

Interpretations

1. CVA says you should have only one issue per commonality. Why is this important?
Having two issues per commonality leads to confusion in the relationship amongst the concepts.
When the connection is clear, then there is clear and thus strong cohesion amongst concepts.
2. How do CVA and design patterns complement each other?
CVA helps to identify what the essential concepts are. Design patterns do not necessarily lead to that.
Design patterns tell you what to do with those concepts, how to relate them based upon good designs from the past. CVA does not speak about best-practices, leaving that to the designer's imagination.

Opinions and Applications

1. I state that experienced developers - even more than inexperienced ones - often focus on entity relationships too early, before they are clear what the right entities are. Is that your experience? Give an example to confirm or refute this statement.
2. Relate the approach to design - starting with CVA - with Alexander's approach.

Chapter 16: The Analysis Matrix

Observations

1. What goes in the far left column of the Analysis Matrix?
The essential concept represented by a function.
2. What do the rows of the Analysis matrix represent?
Each row represents specific, concrete implementations of the generalized concept described in the row.
3. What do the columns of the Analysis matrix represent?
Each column represents the specific implementations for each case
4. Which patterns described in this book might be present in an Analysis Matrix?
In general, any pattern that uses polymorphism could be present in an Analysis Matrix. In this book, that involves Bridge, Decorator, Template, and Observer.

Interpretations

1. At what level of perspective does the Analysis Matrix operate?
The Analysis Matrix is focused on variations in concepts. It is used at the Conceptual Level
2. In what way is the Analysis Matrix similar to Commonality/Variability Analysis?
The Analysis Matrix is focused on variations in concepts. It starts by understanding the concept that a function represents and putting a label onto it. The Analysis Matrix works with these labels as abstractions for the function. CVA also works by abstracting variations and labeling them.

Opinions and Applications

1. Can patterns help handle variation more efficiently?
2. Do you agree with I' observations about users (p. 296)? Can you give examples from your own experience?
3. Do you believe that the Analysis Matrix is generally useful in most problem domains?

Chapter 17: The Decorator Pattern

Observations

1. What does each Decorator object wrap?
Decorators wrap their trailing objects. Each Decorator object wraps its new function around its trailing object.
2. What are two classic examples of decorators?
Heading and footers
Stream I/O

Interpretations

1. How does the Decorator pattern help to decompose the problem?
The Decorator pattern helps to decompose the problem into two parts: How to implement the objects that give the new functionality; and how to organize the objects for each special case
2. In discussing the essence of the Decorator, I say that "the structure is not the pattern." What does this mean? Why is this important?
The Decorator pattern comes into play when there are a variety of optional functions that can precede or follow another function that is always executed.
Implementing the pattern by rote can lead to bad design. Instead, you need to think about the forces at work in the pattern and then think about ways to implement the intent of the pattern. Patterns are not recipes.

Opinions and Applications

1. Why do you think the Gang of Four call this pattern "Decorator"? Is it an appropriate name for what it is doing? Why or why not?
2. Sometimes, people think of patterns as recipes. What is wrong with this?

Chapter 18: The Observer Pattern

Observations

1. According to the Gang of Four, what are structural patterns responsible for?
Structural patterns are used for tying together existing functionality.
2. What are the three classifications of patterns, according to the Gang of Four? What is the fourth classification that I suggest?
The GoF specified three types: Structural, Behavioral, and Creational. I suggest "decoupling" as a fourth type.
3. What is the one true thing about requirements?
Requirements always change! Plan for it.
4. What is the intent of the Observer pattern?
The Gang of Four says that the intent of the Observer pattern is to "define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Interpretations

1. Why are the Bridge and Decorator patterns more correctly classified as structural rather than behavioral patterns?
They both are tying together functionality, which is what structural patterns do. In the Bridge pattern, we typically start with abstractions and implementations and then bind them together with the bridge. In the Decorator pattern, we have an original functional class, and want to decorate it with additional functions.
2. One example of the Observer pattern from outside of software is a radio station: It broadcasts its signal; anyone who is interested can tune in and listen when they want to. What is another example from "real-life"?
Newspaper publishing could be another example
3. Under what conditions should an Observer pattern not be used? When the dependencies are fixed (or virtually so), adding an Observer pattern probably just adds complexity.

Opinions and Applications

1. I put forward the idea of a "fourth category" of patterns, that somewhat includes patterns from other categories. Is this a good idea? Why or why not?

Chapter 19: The Template Method Pattern

Observations

1. The Template Method pattern makes the method call in a special way. What is that?
The method itself is general. It makes the method call via a reference pointing to one of the derived classes to handle the special details.

Interpretations

1. According to the Gang of Four, the intent of the Template Method pattern is to "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Redefine the steps in an algorithm without changing the algorithm's structure" What does this mean?
It helps us to generalize a common process - at an abstract level - from a set of different procedures. It helps to identify the common ground between the set of different procedures while encapsulating the differences in derived classes
2. The Gang of Four calls this a "Template Method". Why do they do this?
Because it provides a boilerplate (or a "template") that specifies the generic actions and derived class implements the specific steps required for the actions to take
3. What is the difference between the Strategy pattern (chapter 9) and the Template Method pattern?
The Template Method pattern is applicable when there are different, but conceptually similar processes.
The Strategy pattern controls a family of algorithms. They do not have to be conceptually similar. You choose the algorithm to employ just in time.

Chapter 20: Lessons from Design Patterns: Factories

Observations

1. How do I define a factory?
A factory is a method, an object, or anything else that is used to instantiate other objects.
2. Name one factory pattern that was shown in a previous chapter. Name the factory patterns mentioned in this chapter
The Abstract Factory was shown in chapter 11. In this chapter, the factories mentioned are Builder, Factory Method, Prototype, and Singleton
3. When it comes to managing object creation, what is a good, universal rule to use?
An object should either make and/or manage other objects, or it should use other objects but it should never do both

Interpretations

1. I state that developers who are new to object-oriented programming often lump the management of object creation in with object instantiation. What is wrong with this?
It can lead to decreased cohesion because an object depends on or more other objects to ensure work is done before it can successfully continue.
2. I suggest that factories increase cohesion. What is their rationale for saying so?
Factories help to keep together both the functionality and the rules that determine which objects should be built and/or managed under different circumstances.
3. I suggest that factories also help in testing. In what ways is this true?
The "using objects" should behave in exactly the same way with any set of derivatives present. I should not need to test every possible combination, because I can test each piece individually. No matter how I combine them, the system will work in the same manner.

Opinions and Applications

1. I suggest that factories are useful for more than simply deciding which object to create or use. They also help with encapsulating design by solving a problem created by patterns? Evaluate this argument.

Chapter 21: The Singleton Pattern and the Double-Checked Locking Pattern

Observations

1. What type of pattern is the Singleton? What general category of pattern does it belong to?
It is a type of Factory pattern
2. What is the intent of the Singleton pattern?
Ensure a class only has one instance, and provide a global point of access to it
3. How many objects is the Singleton responsible for creating?
one
4. The Singleton uses a special method to instantiate objects. What is special about this method?
When this method is called, it checks to see if the object has already been instantiated. If it has, the method simply returns a reference to the object. If not, the method instantiates it and returns a reference to the new instance.
To ensure that this is the only way to instantiate an object of this type, I define the constructor of this class to be protected or private.
5. What do I say is the difference in when to use the Singleton and Double-Checked Locking patterns?
The distinction between the patterns is that the Singleton pattern is used in single-threaded applications while the Double-Checked Locking pattern is used in multithreaded applications. Double-Checked must focus on synchronization in creations in case two objects try to create an object at exactly the same moment. This avoids unnecessary locking. It does this by wrapping the call to new with another conditional test. Singleton does not have to worry about this.

Interpretations

1. I state that they would rather have the objects be responsible for handling their own single instantiation than to do it globally for the objects. Why is this better?
It is encapsulation of behavior: it helps objects be less dependent on some other object to do something that will directly impact what that object can do.
It also frees other objects from worrying whether the object already exists. They can assume it does (or will) and that there is only one of that object to reference. They don't have to worry about getting the right one. As systems grow in size and complexity, trying to manage all of this quickly can get out of hand. But you have to be careful not to create global variables.

Opinions and Applications

2. Why do you think the Gang of Four call this pattern "Singleton"? Is it an appropriate name for what it is doing? Why or why not?
3. The authors state, "When it was discovered that the Double Checked Locking pattern as initially described did not work in Java, many people saw it as evidence that patterns were over-hyped. I drew exactly the opposite conclusion." Do you agree with their logic? Why or why not?

Chapter 22: The Object Pool Pattern

Observations

1. What three general strategies do I suggest you follow?
Look for ways to insulate yourself from the impacts of changes to your system.
Focus on the hard things first
Trust your instincts.
2. What two patterns does the Object Pool pattern incorporate?
The Singleton pattern ensures that only one
The Factory pattern manages the creation and logic
3. What is the intent of the Object Pool pattern? Manages the reuse of objects when a type of object is expensive to create or only a limited number of objects can be created

Interpretations

1. What do the XP community mean by YAGNI?
You Aint Gonna Need It
It reflects the idea that you should build what you need now while ignoring the rest. You should work on the most important things early, when solving them can make the greatest impact. It also means you avoid working on things are at a minimum distracting, and typically never used (and therefore building is a waste of resources).

Opinions and Applications

1. Reading widely is an important discipline. You never know when you will find something you can use. One example is the example they found from Steve Maguire's book, Writing Solid Code. Give at least one example from your own experienced where this has been true for you.

Chapter 23: The Factory Method Pattern Observations

1. What are factories responsible for?
Factories are responsible for creating objects and ensuring objects are available to be used.
2. What is the essential reason to use a Factory Method?
You want to defer the decision for instantiating a derivation of another class to a derived class
3. The Factory Method pattern has been implemented in all of the major object-oriented languages. How has it been used in Java, C#, and C++?
In Java, the iterator method on collections is a Factory Method.
In C#, the GetEnumerator is a Factory method on the differen C# collections where it is present. In C++, the methods used include begin() and end().

Interpretations

1. Why is this pattern called a "factory method?"
It uses a method to handle the factory
2. How does the Factory Method pattern fit in with other factories?
The Factory Method allows these other patterns to defer instantiation to subclasses. One uses the Factory Method to defer responsibility to subclass objects. The Abstract Factory can use a family of Factory Methods, one for each different family of objects involved. The Template Method can use a method to handle the instantiation; giving responsibility to that method is the factory.
3. The Gang of Four says that the intent of the Factory Method is to "define an interface for creating an object, but let subclasses decide which class to instantiate." Why is this important?
It is not always desirable for a class to have to know how to instantiate derived classes

Opinions and Applications

4. How should you go about deciding whether a method should be public, private, or protected?
5. This is a small chapter but this is not a small pattern. Think of one example where this pattern could be used.

Chapter 24: Summary of Factories

No Review Questions in this summary chapter. 

Chapter 25: Design Patterns Reviewed From Our New Perspective of Object-Oriented Principles

Observations

1. Several of the patterns have the characteristic of shielding implementations from what? What is this called? Give examples.
They shield implementation details from the Client object. This is one type of encapsulation. Bridge is one such pattern: It hides from the Client how the Abstraction is implemented.
2. What is one example of a pattern helping to think about decomposing responsibilities?
The Decorator pattern gives a way of decomposing responsibilities into the main set that are always used (ConcreteComponent) and variations that are options (decorators).
3. As you learn patterns, what five forces and concepts do I urge you to look for?
The five forces to look for are:
What implementations does this pattern hide?
What commonalities are present in this pattern?
What are the responsibilities of the objects in this pattern?
What are the relationships between these objects?
How may the pattern itself be a microcosmic example of designing by context?

Interpretations

1. What is the value of hiding implementations?
The patterns allow for adding new implementations by hiding details of current implementations. This reflects the open-closed principle, making systems easier to endure over time

Advance Java Blogging

Java New Articles

Javas Latest News

Java Web Services and XML

Ajax Latest News

Mac OS Java Features

Advance Spotlights

Patterns Features