Design booklet
-
Upload
boris-farber -
Category
Technology
-
view
260 -
download
4
Transcript of Design booklet
9/6/2013
2
Plan
Notion of Class
Inheritance
Interfaces
Abstract Classes
SOLID
Testing
Unit testing
Isolation frameworks
Object Oriented is the most widespread programming
paradigm and supported by major modern languages Java and
C#.
9/6/2013
3
Idea – problem and solution domain entries first class citizens as objects
Mechanics - object as encapsulation for data with services on data. Convenient for interaction based designs.
Interchangeability principle – object can stand for another object (polymorphism)
Class gives semantics to dispatch. Pure Object Oriented is based on hard interfaces with no types (because types expose implementation i.e. can’t change without breaking)
Naming – classes nouns what it is (not what it does e.g. ConverterXXX). Methods/Functions verbs Related to procedures’ naming from previous item what it does (convertXXX).
Object An object is a piece of memory, (bits) that has a type.
9/6/2013
4
UML basics - Class Diagram
Classes, Objects, Associations Class is a construct that is used as a blueprint (or template)
to create objects of that class.
This blueprint describes the state and behavior that the
objects of the class all share.
An object of a given class is called an instance of the class.
The class that contains (and was used to create) that instance
can be considered as the type of that object, e.g. an object
instance of the "Fruit" class would be of the type "Fruit“
Class is an implicit interface
9/6/2013
5
Class Design
Use classes to say "What objects are."
A class is a blueprint for objects
Because objects represent things, class names should be
nouns
The class maps a name to a set of services offered by the
methods in the public interface
The set of services defines what it means to be an instance of
the named class
Inheritance Compartmentalize and reuse code by creating collections of
attributes and behaviors called objects which can be based on
previously created objects.
The new classes, known as Sub-classes (or derived classes),
inherit attributes and behavior of the pre-existing classes,
which are referred to as Super-classes (or ancestor classes)
9/6/2013
6
Inheritance
Compartmentalize and reuse code by creating collections of
attributes and behaviors called objects which can be based on
previously created objects. The new classes, known as Sub-
classes (or derived classes), inherit attributes and behavior of
the pre-existing classes, which are referred to as Super-
classes (or ancestor classes)
Employ inheritance when you have taxonomy
(arrangement) request
Enforce is a permanent relation. Make sure that inherited
class object is a basic class object
Explicitly program for or prevent
9/6/2013
7
Polymorphism
Is the ability of one type, A, to appear as and be used like
another type, B
The primary usage of polymorphism in industry is the ability
of objects belonging to different types to respond to method,
field, or property calls of the same name, each one according
to an appropriate type-specific behavior
Abstract Classes Provide default behavior or define a family
An abstract class is a class that cannot be instantiated. Such a
class is only meaningful if the language supports inheritance.
An abstract class is designed only as a parent class from which
child classes may be derived.
Abstract classes are often used to represent abstract concepts
or entities. The incomplete features of the abstract class are
then shared by a group of subclasses which add different
variations of the missing pieces.
9/6/2013
8
OO Usages
An abstract class is a class that cannot be instantiated. Such a
class is only meaningful if the language supports inheritance.
An abstract class is designed only as a parent class from which
child classes may be derived.
Abstract classes are often used to represent abstract concepts
or entities. The incomplete features of the abstract class are
then shared by a group of subclasses which add different
variations of the missing pieces.
OO Usages cont Abstract definition of an interface. Declare the abstract class with
the methods and their signatures, and publish that as an interface.
Clients see only the abstract class. The implementation inherits
from the abstract class and handles the actual function calls.
Abstract parameter object (not needed in dynamic type
languages). A method can take an abstract class as a parameter and
handle any subtype in the actual call (Closure/Template Method +
Strategy ). This allows for generic services to be created to accept
a generic (abstract) object, but get a real, possibly extended,
object in the actual call. This is the main use of abstract classes
even in languages like Java.
9/6/2013
9
Abstract Class Refactroing
Finding Abstract Classes Abstract classes are discovered by
generalizing from concrete classes.
To give classes a common super class:
Give operations common interface
Move operations with same implementation to super class
Make operations with different implementation abstract
Interfaces A protocol or interface is what or how unrelated objects use
to communicate with each other.
These are definitions of methods and values which the objects
agree upon in order to cooperate.
9/6/2013
10
Interface vs Abstract Class
How do you choose between an abstract class and
an interface? If you have default behavior, then you must use
an abstract class, otherwise, use an interface unless you want
to communicate limits.
SOLID/Clean Code 1. Single Responsibility Principle – Class single reason to change/Object has to do
one thing and do it well. There should never be more than one reason for a class to change (responsibility).
2. Open/Closed Principle – Software entities should be open for extension but close for modification. Law of Demeter x.y.z.d.
3. Liskov Substitution Principle – Objects in a program should be replaceable with instances of their subtypes without altering the correctness of the program
4. Interface Segregation Principle – Many client specific interfaces are better than one general purpose interface. Expose interfaces by functionality. Client’s code easier to read and write.
5. Dependency Inversion Principle – High level modules should not depend on low level modules. Both should depend upon abstractions. Abstractions should not depend upon details, details should depend upon abstractions. Isolation & mocking, don’t use "new" because it is a concrete class.
9/6/2013
11
Composition/Inheritance
Use composition to enlist the help of other objects.
Inheritance makes the design fragile because if you want to
change the super class, you must know all the details of the
subclasses to avoid breaking them.
In composition the coupling is reduced by just having some
smaller things you plug into something bigger, and the bigger
object just calls the smaller object back.
Performance
Unit Testing 1.Run subsystems in isolation (interfaces IoC) modularity
2.Parameters
3.Continuous Integration – running all the unit tests on each commit
4.Shape thinking and APIs – test driven
5.Managed Safety net to perform changes
6.Robust Code
* No logic ifs and be aware of for loops
Naming conventions:
1. Test Class Name - <Class under test>Tests
2. Method Name - <class’s under test method>_<scenario>_<result>
9/6/2013
12
Isolation Frameworks
Steps
Mock all the dependencies by interfaces to achieve isolation. If
it can’t be done refactor your code to be more SOLID and pass
interfaces as parameters (abstract parameter object)
Design Patterns Intro
9/6/2013
13
One must know how to design technology systems.
This implies knowledge of
Engineering methods and techniques including domain specific,
generic knowledge
Design artifacts such as patterns and components to facilitate
quality design
All in all patterns are no more than structures how to
connect classes. Using
Polymorphic Objects
Functional programming
Prototype programming
But this is mechanical definition, the real value definition
pattern is a structure or sub-part known immediately not
only to someone who writes the code but also to someone
who reads or uses the code.
9/6/2013
14
Pattern Definition
27
A particular recurring design problem that arises in specific
design contexts, and presents a well-proven generic scheme
for its solution.
The solution scheme is specified by describing its constituent
components, their responsibilities and relationships, and the
ways in which they collaborate
Context(Problem) + Structure(UML and implementation)
A pattern must: Solve a problem- it must be useful!
Have a context - it must describe where the solution can be
used
Recur - it must be relevant in other situations
Teach - It must provide sufficient understanding to tailor the
solution
Have a name - it must be referred to consistently
9/6/2013
15
Design Patterns are tools
Patterns provide common framework and terms to discuss
work.
However one should remember that design patterns are a
tool, a means to an end, a way to reuse knowledge of what
has gone before.
They are not the ends in themselves
Design Patters – Format & Structure Christopher Alexander and "A Timeless Way of Building“
A pattern is a careful description of a perennial solution to a recurring problem
within a building context, describing one of the configurations which brings life
to a building.
Each pattern describes a problem which occurs over and over again in our
environment, and then describes the core solution to that problem, in such a
way that you can use the solution a million times over, without ever doing it the
same way twice."
A pattern language is a network of patterns that call upon one another. Patterns
help us remember insights and knowledge about design and can be used in
combination to create solutions.
9/6/2013
16
Design Patterns are not !
Patterns fetish
Try to incorporate as much patterns as possible
Wrong/incomplete understanding of the context
Design Patterns are not only for Object
Oriented Design
Functional Programming is a programming paradigm that
treats computation as the evaluation of mathematical
functions and avoids state and mutable data.
Functional Programming Patterns
Recursion
OO patterns expressible in function programming
Strategy
Visitor
9/6/2013
17
Benefits
Design patterns enable large-scale reuse of software
architectures. They also help document systems to enhance
understanding
Patterns explicitly capture expert knowledge and design
tradeoffs, and make this expertise more widely available
Patterns help improve developer communication. Pattern
names form a vocabulary
Patterns help ease the transition to object-oriented
technology (refactoring …)
Drawbacks Patterns do not lead to direct code reuse
Patterns are deceptively simple
Teams may suffer from pattern overload
Patterns are validated by experience and discussion rather
than by automated testing
Integrating patterns into a software development process is a
human-intensive activity
9/6/2013
18
Gang Of Four
Gang of 4 Intro The book's authors are Erich Gamma, Richard Helm, Ralph
Johnson and John Vlissides with a foreword by Grady Booch.
They are often referred to as the Gang of Four, or GoF
The book is divided into two parts, with the first two
chapters exploring the capabilities and pitfalls of object-
oriented programming, and the remaining chapters
describing 23 classic software design patterns
9/6/2013
19
GoF Pattern Structure Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern.
Intent: A description of the goal behind the pattern and the reason for using it.
Also Known As: Other names for the pattern.
Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used.
Applicability: Situations in which this pattern is usable; the context for the pattern.
Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose.
Participants: A listing of the classes and objects used in the pattern and their roles in the design.
Collaboration: A description of how classes and objects used in the pattern interact with each other.
Consequences: A description of the results, side effects, and trade offs caused by using the pattern.
Implementation: A description of an implementation of the pattern; the solution part of the pattern.
Sample Code: An illustration of how the pattern can be used in a programming language
Known Uses: Examples of real usages of the pattern.
Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.
GoF Patterns Creational
Singleton
Prototype
Abstract Factory
Factory Method
Builder
Structural
Proxy
Façade
9/6/2013
20
Cont
Structural
Composite
Decorator
Adapter
Flyweight
Bridge
Behavioral
Observer
Command
State
Cont Behavioral
Iterator
Interpreter
Mediator
Memento
Visitor
Template Method
Strategy Chain of Responsibility
9/6/2013
21
Requirements Engineering
Plan Functional Requirements
Non Functional Requirements
Problem Domain
Solution Domain
Problem Solution Domain mapping
9/6/2013
22
Functional Requirements
Functional requirement is a service/useful work of
a software system or its component.
Functional requirement might be implemented via statement
block or function. A function is described as a set of inputs,
contract, and outputs (see also software).
Functional requirements may be calculations, technical
details, data manipulation and processing and other specific
functionality that define what a software product is supposed to
accomplish. The trivial example could be some mathematical
function or drawing triangle.
Enumerating Functional Requirements
Do table with entities (nouns) and actions (verbs) of the
software product.
From step 1 define problem entities and relationships, as
sentences translated to functional requirements
9/6/2013
23
Non Functional Requirements
The non - functional requirements are the fundamental to
building the successful software products (and systems).
Not only successful Software Systems managed to get their
Non Functional Requirements right, but also we spend most
of our time on non-functional requirements!
Non Functional Requirement(s) is a requirement that
specifies criteria that can be used to judge the
operation of a system, rather than specific
behaviors.
Thus may not be reduced to single entry point in program
(for example it might require to re-implement major part of
system to make it scalable), but rather constraint on
functional requirement or requirements.
9/6/2013
24
Non-functional requirements are often called qualities of a
system. Other terms for non-functional requirements are
"constraints", "quality attributes", "quality goals", "quality
of service requirements" and "non-behavioral requirements”.
Out of respectful plethora on non functional requirements I
find the following three as the most important ones which
are part of evolution qualities (which are embodied in the
static structure of the software system).
Maintaince
Scalability
Portability
Testability
9/6/2013
25
Problem Domain You are Domain Expert (implement a whole domain with few
packages/classes/methods …).Problem Domain is a world where the software product requirements exist. Technically speaking Conceptual model which describes the:
Various entities
Attributes and relationships
Scope and Constraints
All entities and relationships related to the problem. Functional requirements – one sentences describing the functionality of the system. Design Problem Domain artifacts by mapping to Functional Requirements. Note that the software can’t be simpler than the Problem Domain (usually much more complicated).
Solution Domain Conceptual model to cover the use cases of the Problem
Domain, which describes the:
All entities and relationships related to the “implementation“ of
the problem
Analysis and Architectural Patterns
Design Patterns
9/6/2013
26
Design Solution Domain artifacts by implementing the
services required by the Problem Domain. Solution domain
is greater than the Problem domain, because Solution
Domain adds entries that are taken from granted in Problem
Domain (such as factory).
Pieces of Solution Domain that supposed to be generic and
solve more problems got to get out to infrastructure , thus
provide services to solve many problems, not only ours.
Problem Solution Domain Separation
Requirement from the user to software product. For
example show UI… Problem domain
Requirement from the product to the product. For example
support threads Solution domain e.g. factory.
9/6/2013
27
Common mistake from users to tend to mismatch between problem and solution domain by throwing buzzwords they have heard, or rushing to the only solution they know viewing the programming world from the wrong end - the solution domain. Programming is not about using these or other tools of the solution platform. Good programming - in any paradigm - has always relied upon the understanding of the problem domain - i.e. requirement-analysis and design. This is where the important decisions are made. Having convenient tools to implement design decisions is a boost, but not the main issue. Taken from
http://www.linkedin.com/groupAnswers?viewQuestionAndAnswers=&discussionID=67342857&gid=2758278&commentID=49494121&goback=%2Enmp_*1_*1_*1_*1_*1_*1&trk=NUS_DIG_DISC_Q-ucg_mr#commentID_49494121
Problem Solution Food Chain Problem domain for one is solution domain for other. If
someone comes to you, he is problem domain
9/6/2013
28
Design Steps When designing/maintaining software use the following
template to sort out and document your steps. Note this is not linear, you may find yourself juggling between the sections.
Steps
1. Define Objectives
2. Identify Functional Requirements
3. Design Problem Domain artifacts by mapping to Functional Requirements
4. Design Solution Domain artifacts by implementing the services required by the Problem Domain
Map Problem Solution Domain (http://www.swskilltree.org/DesignPatterns/1/2/7.html)
9/6/2013
29
Mapping
Problem Domain
Map Domain entries 1:1 (no optimizations here!), from the
table above.
Use Problem Domain names
Use clear architecture
Solution Domain (control, data, naming)
Use Design Patterns
Use Language Idioms
Design Pitfalls Over engineering – attempting to create beautiful software
without a thought understanding of problem domain.
Under engineering, lack of SOLID
9/6/2013
30
Creational Patterns
9/6/2013
31
Singleton
Singleton Functional Requirement Ensure a class has only one instance, and provide a global
point of access to it.
Encapsulated “just-in-time initialization” or “initialization on
first use”.
9/6/2013
32
Singleton
Solution Define a private static attribute in the “single instance” class.
Define a public static accessor function in the class.
Do “lazy initialization” (creation on first use) in the
accessor function.
Define all constructors to be protected or private.
Clients may only use the accessor function to manipulate
the Singleton.
9/6/2013
33
Analysis Abstract Factory can use Singleton in their implementation.
Facade and State objects are often Singletons because only one Facade or State object is required.
The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton, and, you can change your mind and manage any number of instances.
The Singleton design pattern is one of the most inappropriately used patterns. Singletons are intended to be used when a class must have exactly one instance, no more, no less.
Analysis When is Singleton unnecessary? most of the time. Long
answer: when it’s simpler to pass an object resource as a
reference to the objects that need it, rather than letting
objects access the resource globally.
The real problem with Singletons is that they give you such a
good excuse not to think carefully about the appropriate
visibility of an object. Finding the right balance of exposure
and protection for an object is critical for
maintaining flexibility.
9/6/2013
34
Prototype
Prototype Functional Requirement Application “hard wires” the class of object to create in each
“new” expression.
Co-opt one instance of a class for use as a sample of all
future instances.
9/6/2013
35
Prototype
Solution Declare an abstract base class that specifies a pure
virtual clone() method. Any class that needs a
"polymorphic constructor" capability derives itself from the
abstract base class, and implements the clone() operation.
The client, instead of writing code that invokes the "new"
operator on a hard-coded class name, calls the clone() method
on the prototype, calls a factory method with a parameter
designating the particular concrete derived class desired, or
invokes the clone() method through some mechanism.
9/6/2013
36
Analysis Abstract Factory classes are often implemented with Factory
Methods, but they can be implemented using Prototype.
Factory Method: creation through inheritance. Prototype: creation through delegation.
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize.
Analysis
Prototype is unique among the other
creational patterns in that it doesn’t
require a class – only an object (the
client doesn’t know the exact class
being copied)
Prototypes are useful when object initialization
is expensive, and you anticipate few variations
on the initialization parameters.
9/6/2013
37
Prototype Based Programming
Idea – behavioral reuse by cloning (and not via sub-typing)
and changing. That is arranging objects without class notion
(paradigm shift classic Object Oriented is class based) by
rather changing small parts of the objects.
The principle is that most objects are derived from other,
more general objects, and only differ in a few small aspects.
Thus the power of object is not its class but its values.
Prototype Based Programming Contd’
Mechanics - Polymorphism not via sub-typing – prototype based Io – map with pointers + pointer father and on…
Differential inheritance is implemented by maintaining a list of pointers internally to other objects which the object differs from.
Note in a sense this like implementing the symbol table of a complier.
Io/Self/Lua programming language, classless object oriented. Pointers can be pointer to function (first class citizens).
9/6/2013
38
Abstract Factory
9/6/2013
39
Abstract Factory Functional
Requirement
If an application is to be portable, it needs to encapsulate
platform dependencies.
windowing system
operating system
database, etc.
Too often, this encapsulation is not engineered in advance,
and lots of #ifdefs …
Abstract Factory
9/6/2013
40
Solution
Provide an interface for creating families of related or
dependent objects without specifying their concrete classes.
A hierarchy that encapsulates: many possible “platforms”, and
the construction of a suite of “products”.
The new operator considered harmful.
Structure Decide if “platform independence” and creation services are
the current source of pain.
Map out a matrix of “platforms” versus “products”.
Define a factory interface that consists of a factory method
per product.
Define a factory derived class for each platform that
encapsulates all references to the new operator.
The client should retire all references to new, and use the
factory methods to create the product objects.
9/6/2013
41
Analysis
Sometimes creational patterns are competitors: there are
cases when either Prototype or Abstract Factory could be
used profitably. At other times they are complementary:
Abstract Factory might store a set of Prototypes from which
to clone and return product objects, Builder can use one of
the other patterns to implement which components get built.
Builder focuses on constructing a complex object step by
step. Abstract Factory emphasizes a family of product objects
(either simple or complex). Builder returns the product as a
final step, but as far as the Abstract Factory is concerned, the
product gets returned immediately
Factory Method
9/6/2013
42
Factory Method Functional
Requirement
A framework needs to standardize the architectural model
for a range of applications
A framework needs allow for individual applications to define
their own domain objects and provide for their instantiation.
Factory Method
9/6/2013
43
Solution
Define an interface for creating an object, but let subclasses
decide which class to instantiate. Factory Method lets a class
defer instantiation to subclasses.
Defining a “virtual” constructor.
The new operator considered harmful.
Solution If you have an inheritance hierarchy that exercises
polymorphism, consider adding a polymorphic creation
capability by defining a static factory method in the
base class.
Design the arguments to the factory method. What qualities
or characteristics are necessary and sufficient to identify the
correct derived class to instantiate?
Consider designing an internal “object pool” that will allow
objects to be reused instead of created from scratch.
Consider making all constructors private or protected.
9/6/2013
44
Analysis Abstract Factory classes are often implemented
with Factory Methods, but they can be implemented using Prototype.
Factory Method: creation through inheritance. Prototype: creation through delegation.
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
Analysis Prototype doesn’t require subclassing, but it does require an
Initialize operation. Factory Method requires subclassing, but doesn’t require Initialize.
The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact type.
The new operator considered harmful. There is a difference between requesting an object and creating one. The new operator always creates an object, and fails to encapsulate object creation. A Factory Method enforces that encapsulation, and allows an object to be requested without inextricable coupling to the act of creation.
9/6/2013
45
Factory
Builder
9/6/2013
46
Builder Functional Requirement
An application needs to create the elements of a complex
aggregate.
Builder
9/6/2013
47
Solution
To abstract steps of construction of objects so that different
implementations of these steps can construct different
representations of objects.
Often, the Builder Pattern is used to build Products in
accordance to the Composite pattern, a structural pattern
(i.e. create a recursive structures)
Solution (Builder + Composite) 1. Create a builder class, can produce one composite node.
2. Make builder capable of building children (includes
multiple methods for children direct creation and
positions)
3. If needed (by composite) make builder setting attributes
and values
4. Refactor composite code to use the builder
9/6/2013
48
Analysis
Builder focuses on constructing a complex object step by
step.
Builder returns the product as a final step, but as far as
the Abstract Factory is concerned, the product gets returned
immediately.
Builder often builds a Composite.
Builder is a Strategy of Factory (thanks to O.Lutzky)
Structural Patterns
9/6/2013
49
Structural Patterns
Are patterns that ease the design by identifying a simple way
to realize relationships between entities.
Structural Patterns 1 The following patterns don’t use polymorphism
Proxy
Façade
9/6/2013
50
Proxy
Proxy Functional Requirement We need to support resource-hungry objects, and you do not
want to instantiate such objects unless and until they are
actually requested by the client.
9/6/2013
51
Proxy
Solution Provide a surrogate or placeholder for another object to
control access to it.
Use an extra level of indirection to support distributed,
controlled, or intelligent access.
Add a wrapper and delegation to protect the real component
from undue complexity.
9/6/2013
52
Solution Identify the leverage or “aspect” that is best implemented as a
wrapper or surrogate.
Define an interface that will make the proxy and the original
component interchangeable.
Consider defining a Factory that can encapsulate the decision of
whether a proxy or original object is desirable.
The wrapper class holds a pointer to the real class and implements
the interface.
The pointer may be initialized at construction, or on first use.
Each wrapper method contributes its leverage, and delegates to
the wrappee object.
Analysis Adapter provides a different interface to its subject. Proxy
provides the same interface. Decorator provides an
enhanced interface.
Decorator and Proxy have different purposes but similar
structures. Both describe how to provide a level of
indirection to another object, and the implementations keep
a reference to the object to which they forward requests.
9/6/2013
53
Facade
Façade Functional Requirement Provide a unified interface to a set of interfaces in a
subsystem
9/6/2013
54
Façade
Solution Facade defines a higher-level interface that makes the
subsystem easier to use.
Wrap a complicated subsystem with a simpler interface.
9/6/2013
55
Façade Solution
Identify a simpler, unified interface for the subsystem
or component.
Design a ‘wrapper’ class that encapsulates the subsystem.
The facade/wrapper captures the complexity and
collaborations of the component, and delegates to the
appropriate methods.
The client uses (is coupled to) the Facade only.
Analysis Facade defines a new interface, whereas Adapter uses an old interface.
Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communications between colleague objects. It routinely “adds value”, and it is known/referenced by the colleague objects. In contrast, Facade defines a simpler interface to a subsystem, it doesn’t add new functionality, and it is not known by the subsystem classes.
Facade objects are often Singletons because only one Facade object is required.
The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design to an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object
9/6/2013
56
Structural Patterns 2
The following patterns use polymorphism
Composite
Decorator
Adapter
Flyweight
Bridge
Composite
9/6/2013
57
Composite Functional Requirement
Represent a group of objects that are to be treated in the
same way as a single instance of an object
Composite
9/6/2013
58
Solution
Compose objects into tree structures to represent whole-
part hierarchies. Composite lets clients treat individual
objects and compositions of objects uniformly.
Recursive composition
“Directories contain entries, each of which could be
a directory.”
1-to-many “has a” up the “is a” hierarchy
Solution Ensure that your problem is about representing “whole-part” hierarchical relationships.
Consider the heuristic, “Containers that contain containees, each of which could be a container.”
Divide your domain concepts into container classes, and containee classes.
Create a “lowest common denominator” interface that makes your containers and containees interchangeable. It should specify the behavior that needs to be exercised uniformly across all containee and container objects.
All container and containee classes declare an “is a” relationship to the interface.
All container classes declare a one-to-many “has a” relationship to the interface.
Container classes leverage polymorphism to delegate to their containee objects.
Child management methods [e.g. addChild(), removeChild()] should normally be defined in the Composite class. Unfortunately, the desire to treat Leaf and Composite objects uniformly may require that these methods be promoted to the abstract Component class.
9/6/2013
59
Analysis Composite and Decorator have similar structure diagrams, reflecting the
fact that both rely on recursive composition to organize an open-ended number of objects.
Composite can be traversed with Iterator. Visitor can apply an operation over a Composite
Decorator is designed to let you add responsibilities to objects without subclassing. Composite’s focus is not on embellishment but on representation. These problems are distinct but complementary.
Flyweight is often combined with Composite to implement shared leaf nodes.
Decorator
9/6/2013
60
Decorator Functional Requirement
Extend the functionality of a certain object at runtime,
independently of other instances of the same class.
Decorator
9/6/2013
61
Problem The decorator pattern can be used to make it possible to extend
(decorate) the functionality of a certain object at runtime, independently of other instances of the same class, provided some groundwork is done at design time.
This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps added to an existing object dynamically.
That is the wrapper object adds some work to the original object while keeping the same interface
Solution This pattern is designed so that multiple decorators can be stacked on
top of each other, each time adding a new functionality to the overridden method(s).
The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.
Decorators are objects, created at runtime, and can be combined on a per-use basis. An example of the decorator pattern is the Java I/O Streams implementation.
9/6/2013
62
Adaptor
Adapter Functional Requirement An “off the shelf ” component offers compelling functionality
that you would like to reuse
Unfortunately its “view of the world” is not compatible with
the philosophy and architecture of the system currently
being developed
9/6/2013
63
Adapter
Solution Convert the interface of a class into another interface clients
expect. Adapter lets classes work together that couldn’t
otherwise because of incompatible interfaces.
Wrap an existing class with a new interface.
Impedance match an old component to a new system
9/6/2013
64
Analysis Adapter makes things work after they’re designed; Bridge makes them work before
they are.
Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.
Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
Adapter is meant to change the interface of an existing object. Decorator enhances another object without changing its interface. Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports recursive composition, which isn’t possible with pure Adapters.
Facade defines a new interface, whereas Adapter reuses an old interface. Adapter makes two existing interfaces work together as opposed to defining an entirely new one.
Flyweight
9/6/2013
65
Flyweight Functional Requirement
Designing objects down to the lowest levels of system
“granularity” provides optimal flexibility, but can be
unacceptably expensive in terms of performance and
memory usage.
Flyweight
9/6/2013
66
Flyweight Solution
Use sharing to support large numbers of fine-grained
objects efficiently.
Solution 1. Ensure that object overhead is an issue needing attention,
and, the client of the class is able and willing to absorb responsibility realignment.
2. Divide the target class’s state into: shareable (intrinsic) state, and non-shareable (extrinsic) state.
3. Remove the non-shareable state from the class attributes, and add it to the calling argument list of affected methods.
4. Create a Factory that can cache and reuse existing class instances.
5. The client must use the Factory instead of the new operator to request objects.
6. The client (or a third party) must look-up or compute the non-shareable state, and supply that state to class methods.
9/6/2013
67
Analysis
Whereas Flyweight shows how to make lots of little objects,
Facade shows how to make a single object represent an
entire subsystem.
Flyweight explains when and how State objects can
be shared.
Bridge
9/6/2013
68
Bridge Functional Requirement
"decouple an abstraction from its implementation so that the two can
vary independently"
Bridge
9/6/2013
69
Solution
Decouple an abstraction from its implementation so that the
two can vary independently.
Publish interface in an inheritance hierarchy, and bury
implementation in its own inheritance hierarchy.
Beyond encapsulation, to insulation
Steps Decide if two orthogonal dimensions exist in the domain.
These independent concepts could be: abstraction/platform, or domain/infrastructure, or front-end/back-end, or interface/implementation.
Design the separation of concerns: what does the client want, and what do the implementation provide.
Design a interface that is minimal, necessary, and sufficient. Its goal is to decouple the abstraction from the implementation.
Define and implement a derived class of that interface for each implementation.
9/6/2013
70
Analysis
Adapter makes things work after they’re designed; Bridge
makes them work before they are.
Bridge is designed up-front to let the abstraction and the
implementation vary independently. Adapter is retrofitted to
make unrelated classes work together.
State, Strategy, Bridge (and to some degree Adapter) have
similar solution structures. They all share elements of the
“handle/body” idiom. They differ in Problem - that is, they
solve different problems.
Deck 3 Design Patterns
Polymorphic Behaviour
9/6/2013
71
Plan
Observer
Command
State
Iterator
Interpreter
Mediator
Memento
Obeserver
9/6/2013
72
Observer Functional Requirement
Define a one-to-many dependency between objects so that
when one object changes state, all its dependents are notified
and updated automatically.
Publish/Subscribe event monitoring situation.
Observer
9/6/2013
73
Solution
Define a one-to-many dependency between objects so that
when one object changes state, all its dependents are notified
and updated automatically.
Encapsulate the core (or common or engine) components in
a Subject abstraction, and the variable (or optional or user
interface) components in an Observer hierarchy.
The “View” part of Model-View-Controller.
Solution Differentiate between the core (or independent) functionality and the optional
(or dependent) functionality.
Model the independent functionality with a “subject” abstraction.
Model the dependent functionality with an “observer” hierarchy.
The Subject is coupled only to the Observer base class.
The client configures the number and type of Observers.
Observers register themselves with the Subject.
The Subject broadcasts events to all registered Observers.
The Subject may “push” information at the Observers, or, the Observers may “pull” the information they need from the Subject.
9/6/2013
74
Analysis Chain of Responsibility, Command, Mediator, and Observer, address
how you can decouple senders and receivers, but with different trade-
offs. Chain of Responsibility passes a sender request along a chain of
potential receivers. Command normally specifies a sender-receiver
connection with a subclass. Mediator has senders and receivers reference
each other indirectly. Observer defines a very decoupled interface that
allows for multiple receivers to be configured at run-time.
Mediator and Observer are competing patterns. The difference between
them is that Observer distributes communication by introducing
“observer” and “subject” objects, whereas a Mediator object encapsulates
the communication between other objects.
Command
9/6/2013
75
Command Functional Requirement
Need to issue requests to objects without knowing anything
about the operation being requested or the receiver of
the request
Command
9/6/2013
76
Solution
Encapsulate a request as an object, thereby letting you
parameterize clients with different requests, queue or log
requests, and support un-doable operations.
Promote “invocation of a method on an object” to full
object status
An object-oriented callback
Solution Define a Command interface with a method signature
like execute().
Create one or more derived classes that encapsulate some subset of the following: a “receiver” object, the method to invoke, the arguments to pass.
Instantiate a Command object for each deferred execution request.
Pass the Command object from the creator (aka sender) to the invoker (aka receiver).
The invoker decides when to execute().
9/6/2013
77
Analysis Chain of Responsibility, Command, Mediator, and Observer, address how you can
decouple senders and receivers, but with different trade-offs. Command normally specifies a sender-receiver connection with a subclass.
Chain of Responsibility can use Command to represent requests as objects.
Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
Command can use Memento to maintain the state required for an undo operation.
A Command that must be copied before being placed on a history list acts as a Prototype.
Two important aspects of the Command pattern: interface separation (the invoker is isolated from the receiver), time separation (stores a ready-to-go processing request that’s to be stated later).
State
9/6/2013
78
State Functional Requirement
An object’s behavior is a function of its state, and it must
change its behavior at run-time depending on that state.
An application is characterized by large and numerous case
statements that control the application behavior (Why is it
bad ?)
State
9/6/2013
79
Solution Identify an existing class, or create a new class, that will serve as the “state machine”
from the client’s perspective. That class is the “wrapper” class.
Create a State base class that replicates the methods of the state machine interface. Each method takes one additional parameter: an instance of the wrapper class. The State base class specifies any useful “default” behavior.
Create a State derived class for each domain state. These derived classes only override the methods they need to override.
The wrapper class maintains a “current” State object.
All client requests to the wrapper class are simply delegated to the current State object, and the wrapper object’s this pointer is passed.
The State methods change the “current” state in the wrapper object as appropriate.
Analysis State objects are often Singletons.
Flyweight explains when and how State objects can be shared.
The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.
9/6/2013
80
Iterator
Iterator Functional Requirement Need to “abstract” the traversal of wildly different data
structures so that algorithms can be defined that are capable
of interfacing with each transparently.
9/6/2013
81
Iterator
Problem Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.
The C++, Java and C# standard library abstraction that
makes it possible to decouple collection classes
and algorithms.
Promote to “full object status” the traversal of
a collection.Polymorphic traversal
9/6/2013
82
Solution Add a create_iterator() method to the “collection” class, and grant
the “iterator” class privileged access.
Design an “iterator” class that can encapsulate traversal of the “collection” class.
Clients ask the collection object to create an iterator object.
Clients use the first(), is_done(), next(), and current_item() protocol to access the elements of the collection class.
Analysis The abstract syntax tree of Interpreter is a Composite (therefore
Iterator and Visitor are also applicable).
Iterator can traverse a Composite. Visitor can apply an operation over a Composite.
Polymorphic Iterators rely on Factory Methods to instantiate the appropriate Iterator subclass.
Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.
9/6/2013
83
Interpreter Functional Requirement
A class of problems occurs repeatedly in a well-defined and
well-understood domain. If the domain were characterized
with a “language”, then problems could be easily solved with
an interpretation “engine”.
Interpretator
9/6/2013
84
Interpreter
Problem Given a language, define a representation for its grammar
along with an interpreter that uses the representation to
interpret sentences in the language.
Map a domain to a language, the language to a grammar, and
the grammar to a hierarchical object-oriented design.
9/6/2013
85
Solution Decide if a “little language” offers a justifiable return on investment.
Define a grammar for the language.
Map each production in the grammar to a class.
Organize the suite of classes into the structure of the Composite pattern.
Define an interpret(Context) method in the Composite hierarchy.
The Context object encapsulates the current state of the input and output as the former is parsed and the latter is accumulated. It is manipulated by each grammar class as the “interpreting” process transforms the input into the output.
Analysis Considered in its most general form (i.e. an operation distributed over a class hierarchy
based on the Composite pattern), nearly every use of the Composite pattern will also contain the Interpreter pattern. But the Interpreter pattern should be reserved for those cases in which you want to think of this class hierarchy as defining a language.
Interpreter can use State to define parsing contexts.
The abstract syntax tree of Interpreter is a Composite (therefore Iterator and Visitor are also applicable).
Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight.
The pattern doesn’t address parsing. When the grammar is very complex, other techniques (such as a parser) are more appropriate.
9/6/2013
86
Mediator
Mediator Functional Requirement
We want to design reusable components, but dependencies
between the potentially reusable pieces demonstrates the
“spaghetti code” phenomenon (trying to scoop a single
serving results in an “all or nothing clump”).
9/6/2013
87
Mediator
Solution Define an object that encapsulates how a set of objects
interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Design an intermediary to decouple many peers.
Promote the many-to-many relationships between interacting peers to “full object status”.
9/6/2013
88
Solution Identify a collection of interacting objects that would benefit from
mutual decoupling.
Encapsulate those interactions in the abstraction of a new class.
Create an instance of that new class and rework all “peer” objects to interact with the Mediator only.
Balance the principle of decoupling with the principle of distributing responsibility evenly.
Be careful not to create a “controller” or “god” object.
Analysis Chain of Responsibility, Command, Mediator, and Observer,
address how you can decouple senders and receivers, but with different trade-offs. Mediator has senders and receivers reference each other indirectly.
Mediator and Observer are competing patterns. The difference between them is that Observer distributes communication by introducing “observer” and “subject” objects, whereas a Mediator object encapsulates the communication between other objects.
9/6/2013
89
Analysis On the other hand, Mediator can leverage Observer for dynamically registering
colleagues and communicating with them.
Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communication between colleague objects, it routinely “adds value”, and it is known/referenced by the colleague objects (i.e. it defines a multidirectional protocol). In contrast, Facade defines a simpler interface to a subsystem, it doesn’t add new functionality, and it is not known by the subsystem classes (i.e. it defines a unidirectional protocol where it makes requests of the subsystem classes but not vice versa).
Memento
9/6/2013
90
Memento Functional Requiremenrt
Need to restore an object back to its previous state (e.g.
“undo” or “rollback” operations).
Memento
9/6/2013
91
Solution
Without violating encapsulation, capture and externalize an
object’s internal state so that the object can be returned to
this state later.
A magic cookie that encapsulates a “check point” capability.
Promote undo or rollback to full object status.
Need to restore an object back to its previous state (e.g.
“undo” or “rollback” operations).
Solution Identify the roles of “caretaker” and “originator”.
Create a Memento class and declare the originator a friend.
Caretaker knows when to “check point” the originator.
Originator creates a Memento and copies its state to
that Memento.
Caretaker holds on to (but cannot peek into) the Memento.
Caretaker knows when to “roll back” the originator.
Originator reinstates itself using the saved state in
the Memento.
9/6/2013
92
Analysis Command and Memento act as magic tokens to be passed
around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
Command can use Memento to maintain the state required for an undo operation.
Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration.
Behavioral Patterns 2
Functional Independence
9/6/2013
93
Plan
Visitor
Template Method
Strategy
Chain on Responsibility
Visitor
9/6/2013
94
Visitor Functional Requirement
Many distinct and unrelated operations need to be performed
on various objects (might be part of heterogeneous aggregate
structure).
We want to avoid “polluting” the node classes with these
operations.
We don’t want to have to query the type of each node and
cast the pointer to the correct type before performing the
desired operation.
We don’t want to change the nodes hierarchy
Visitor
9/6/2013
95
Solution
Represent an operation to be performed on the elements of
an object structure. Visitor lets you define a new operation
without changing the classes of the elements on which
it operates.
The classic technique for recovering lost type information.
Do the right thing based on the type of two objects.
Double dispatch
Solution Confirm that the current hierarchy (known as the Element hierarchy) will be fairly stable and that the public
interface of these classes is sufficient for the access the Visitor classes will require. If these conditions are not met, then the Visitor pattern is not a good match.
Create a Visitor base class with a visit(ElementXxx) method for each Element derived type.
Add an accept(Visitor) method to the Element hierarchy. The implementation in each Element derived class is always the same – accept( Visitor v ) { v.visit( this ); }. Because of cyclic dependencies, the declaration of the Element and Visitor classes will need to be interleaved.
The Element hierarchy is coupled only to the Visitor base class, but the Visitor hierarchy is coupled to each Element derived class. If the stability of the Element hierarchy is low, and the stability of the Visitor hierarchy is high; consider swapping the ‘roles’ of the two hierarchies.
Create a Visitor derived class for each “operation” to be performed on Element objects. visit()implementations will rely on the Element’s public interface.
The client creates Visitor objects and passes each to Element objects by calling accept().
9/6/2013
96
Analysis The abstract syntax tree of Interpreter is a Composite (therefore
Iterator and Visitor are also applicable).
Iterator can traverse a Composite. Visitor can apply an operation over a Composite.
The Visitor pattern is like a more powerful Command pattern because the visitor may initiate whatever is appropriate for the kind of object it encounters.
The Visitor pattern is the classic technique for recovering lost type information without resorting to dynamic casts.
Template Method
9/6/2013
97
Template Method Functional
Requirement
Two different components have significant similarities, but
demonstrate no reuse of common interface or
implementation. If a change common to both components
becomes necessary, duplicate effort must be expended
Create a framework
Template Method
9/6/2013
98
Solution
Define the skeleton of an algorithm in an operation,
deferring some steps to client subclasses. Template Method
lets subclasses redefine certain steps of an algorithm without
changing the algorithm’s structure.
Base class declares algorithm ‘placeholders’, and derived
classes implement the placeholders.
Solution Examine the algorithm, and decide which steps are standard and which steps are peculiar to each of
the current classes.
Define a new abstract base class to host the “don’t call us, we’ll call you” framework.
Move the shell of the algorithm (now called the “template method”) and the definition of all standard steps to the new base class.
Define a placeholder or “hook” method in the base class for each step that requires many different implementations. This method can host a default implementation – or – it can be defined as abstract (Java) or pure virtual (C++).
Invoke the hook method(s) from the template method.
Each of the existing classes declares an “is-a” relationship to the new abstract base class.
Remove from the existing classes all the implementation details that have been moved to the base class.
The only details that will remain in the existing classes will be the implementation details peculiar to each derived class.
9/6/2013
99
Analysis Strategy is like Template Method except in its granularity.
Template Method uses inheritance to vary part of an algorithm. Strategy uses delegation to vary the entire algorithm.
Template Method modifies the logic of individual objects. Strategy modifies the logic of an entire class.
Factory Method is a specialization of Template Method
Strategy
9/6/2013
100
Strategy Functional Requirements
We want to define a family of algorithms and make them
interchangeable.
We want let the algorithms vary independently from clients
that use them
Route to Airport via various means
9/6/2013
101
Strategy
Solution Identify an algorithm (i.e. a behavior) that the client would
prefer to access through a “flex point”.
Specify the signature for that algorithm in an interface.
Bury the alternative implementation details in
derived classes.
Clients of the algorithm couple themselves to the interface.
9/6/2013
102
Analysis Strategy is like Template Method except in its granularity.
State is like Strategy except in its Problem.
Strategy lets you change the guts of an object. Decorator lets you change the skin.
State, Strategy, Bridge (and to some degree Adapter) have similar solution structures. They all share elements of the ‘handle/body’ idiom. They differ in Problem - that is, they solve different problems.
Strategy objects often make good Flyweights.
Chain of Responsibility
9/6/2013
103
Chain Of Responsibility Functional
Requirements
There is a potentially variable number of “handler” or
“processing element” or “node” objects, and a stream of
requests that must be handled such as exception handling
mechanism.
9/6/2013
104
Chain of Responsibility
Solution Avoid coupling the sender of a request to its receiver by
giving more than one object a chance to handle the request.
Chain the receiving objects and pass the request along the
chain until an object handles it.
Launch-and-leave requests with a single processing pipeline
that contains many possible handlers.
An object-oriented linked list with recursive traversal.
9/6/2013
105
Solution The base class maintains a “next” pointer.
Each derived class implements its contribution for handling
the request.
If the request needs to be “passed on”, then the derived class “calls
back” to the base class, which delegates to the “next” pointer.
The client (or some third party) creates and links the chain (which
may include a link from the last node to the root node).
The client “launches and leaves” each request with the root of
the chain.
Recursive delegation produces the illusion of magic.
Analysis Chain of Responsibility, Command, Mediator, and Observer,
address how you can decouple senders and receivers, but
with different trade-offs. Chain of Responsibility passes a
sender request along a chain of potential receivers.
Chain of Responsibility can use Command to represent
requests as objects.
9/6/2013
106
Plan
Pattern Languages
Patterns in Context of Solution Domain
Missing Language Features
Paradigm Shifts
Mapping to Change
Summary
9/6/2013
107
Plan
Pattern Languages
Patterns in Context of Solution Domain
Missing Language Features
Paradigm Shifts
Mapping to Change
Patterns Language
Patterns collaborating together to create mini architectures
9/6/2013
108
Useful Pattern Languages Visitor + Decorator – language translation with flexible combination.
Visitor has callbacks for visited language tokens, and custom visitor adds his logic what to do there (say add logic to output array – source translation)
Builder – Strategy of Factory
Builder builds Composite, Composite uses Hierarchical Iterator
Use Chain of Responsibility for exceptions handler code.
Façade/Factory implemented via Singleton
Command + Memento – undo operation
Command copied and placed in history is Prototype
Chain of Responsibility, Command, Mediator, and Observer, address how you can decouple senders and receivers, but with different trade-offs. Chain of Responsibility passes a sender request along a chain of potential receivers.
Patterns Languages cont’ Chain of Responsibility can use Command to represent requests as objects.
Composite and Decorator have similar structure diagrams, reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.
Flyweight is often combined with Composite to implement shared leaf nodes.
State, Strategy, Bridge (and to some degree Adapter) have similar solution structures. They all share elements of the “handle/body” idiom. They differ in Problem - that is, they solve different problems.
Adapter makes things work after they’re designed; Bridge makes them work before they are.
Interpreter/Mini language – passed (in OO as hash table with keys) when the future usage is un-known, such as Android bundle. Basically interpreter is set of functions + dispatcher. Add Composite and got recursive language.
Visitor with decorator, combine visitors dynamically.
9/6/2013
109
Patterns Languages cont’ State versus Strategy - The similarity: An object contains/references another
object, to which it delegates decisions. The difference: A strategy is delegated limited logic, usually less than a method, while the current state responds to all input to the machine. A Strategy is seldom replaced, and when it does, the decision comes from outside, while the current state is constantly being replaced, by the machine, usually decided by the combination of input and previous state
MVC - but a pattern language. Its scope is the whole application, rather than a specific problem. It is concerned with dividing a complete application to modules, and that, as for as l can see, is in the realm of architecture.
Yield/Coroutine - iterator with state machine. State is internal object keeping state. That state always returned as a new object each time GetIterator() is called
Abstract Parameter Object - Template Method + Strategy - reduce coupling
Decorator versus Inheritance Decorator is not inheritance because doesn’t fit
Substitution Principle because it doesn’t know his ancestors
(they are dynamic), while prototype or any other sub-class
does know his super class methods (ok not private).
In class based inheritance and prototype you have one object
+ one method call (given not degenerated code where each
class calling to super). While in decorator you don’t know
how many calls will be performed.
9/6/2013
110
Prototype versus Decorator
Both provide functionality extension without sub-typing.
Decorator provides functionality reuse, while Prototype
provides values + functionality behavioral reuse.
Design Patterns in Context of Solution
Domain
As Language Features, Design Patterns to make up language:
Singleton – no module object
Visitor – no multi-methods
Strategy/Command – no functions acting as first class
objects or high order functions
9/6/2013
111
As Paradigm Shifts - is a change from
one way of thinking to another.
Proxy One object can stand for different object
Decorator flexible alternative to sub-typing – extend the functionality of object at run time (but known at compile time) independent of other objects of the same class. The paradigm shift is one object has more functionality versus the objects of the same class (paradigm all the object of same class have same behavior).
Mediator Handle communication
Template Method don't call us we call you – similar to co-routine – routine where you control the execution points
Paradigm Shifts Prototype - The Meta data comes from instance and not from
class. To prevent application “hardwire” of the object class on
each new object creation.
Strategy – external Meta data. Configuration object that
operates on visited object (Context), not one usage call, but
many usages. Sort of configurable function.
Composite – recursively defined object