INFO3220: Object Oriented Design
20
18
S1INFO3220: Object Oriented Design
Bernhard Scholz
Bernhard.Scholz@sydney.edu.au
School of Information Technologies, University of Sydney
Semester 1, 2018
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 1 / 51
20
18
S1Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969WARNING
This material has been reproduced and communicated to you by or on
behalf of the University of Sydney pursuant to Part VB of the Copyright Act
1968 (the Act).
The material in this communication may be subject to copyright under the
Act. Any further copying or communication of this material by you may be
the subject of copyright protection under the Act.
Do not remove this notice.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 2 / 51
20
18
S11 Lecture 5: Design PatternsDesign Patterns
Redesign
Creational Patterns
2 Lecture 6: The Factory Method and the Abstract Factory Design
Patterns
The Factory Method
Factory Method
The Abstract Factory
Abstract Factory
Comparing the Factory Patterns
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 3 / 51
20
18
S1Topic 5: Design Patterns
Solving problems in OO programming
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 3 / 51
20
18
S1Starting with creational design patterns first
What’s a design pattern and an introduction
to creational design patterns
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 4 / 51
20
18
S1What is a design pattern?A pattern is a description of a problem and its solution. The four essential
components of a pattern in our context are these:
1 The pattern name – e.g., Factory Method;
2 The problem that the pattern is designed to solve;
3 The solution: the components of the design and how they related to
each other in order to solve the problem.
4 The consequences: both advantages and disadvantages of the pattern.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 5 / 51
20
18
S1A Table of Design Patterns PurposeCreational Structural Behavioural
Scope
Class Factory Method Class Adapter InterpreterTemplate Method
Object
Abstract Factory Object Adapter Chain of Responsibility
Builder Bridge Command
Prototype Composite Iterator
Singleton Decorator Mediator
Façade Memento
Flyweight Observer
Proxy State
Strategy
Visitor
You will look at each of these throughout the semester in either the
lectures or the labs or both.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 6 / 51
20
18
S1AdapterBridge
Composite
Decorator
Façade
Proxy
Chain of
Reponsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State Strategy
Template
Method
Visitor
Abstract
Factory
Builder
Factory
Method
Prototype
SingletonFlyweight
Structural
Pattern
Behavioural
Pattern
Creational
Pattern
avoiding
hysteresis
composed
using
saving state
of iteration
creating
composites
adding
responsibilities
to objects
iterating
children
defining
traversals
adding
operations
defining
the chain
sharing
states
sharing
strategies
complex
dependency
management
changing skin
vs internals defining
algorithm’s
steps often
uses
implement
using
single
instance
single
instance
configure factory
dynamically
adding
operations defining
grammar
adapted from the GoF book: Design Patterns
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 7 / 51
20
18
S1Some common reasons to have to redesign a programCreating an object by specifying its class (not its interface)Dependence on specific operationsDependence on platform
Dependence on an object’s representation in memory or
implementation
Dependence on algorithms
Tight coupling: too much dependence between classes
Extending functionality by making subclasses
Inability to conveniently alter classes
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 8 / 51
20
18
S1How design patterns solve design problemsDesign patterns solve problems byfinding and using appropriate objects;determining the objects’ granularity (size)specifying object interfaces;
specifying object implementations;
putting re-use mechanisms to work;
relating run-time and compile-time structures;
designing for change
We will go into these in more detail once we have a few design patterns in
our heads.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 9 / 51
20
18
S1Selecting a Design PatternThere are many design patterns to choose from so it is useful to havesome guidelines of how to select one. Here are some thoughts on how youmight do that:Consider the ways in which the design patterns solve problems We will go
into details on this for several design patterns.
Decide on what the intent of each design is Without knowing what the
motivation of the design pattern is, it will be hard to know
whether it is right for you!
Look at the relationships among patterns It makes sense to use patterns
that have a clear relationship, rather than one that you have
to manufacture ad hoc.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 10 / 51
20
18
S1Selecting a Design Pattern (cont.)Consider patterns with similar purpose Creational, Structural andBehavioural are quite different purposes so you shouldconsider which one you need.Look at why redesign might be necessary Knowing why a redesign might
be needed will help you select the right design to avoid
having to redesign later.
What can vary? Your design should be open to variation where necessary:
choose a design that will not lock you in to a particular one,
and enable you to make variations without changing your
design.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 11 / 51
20
18
S1Showing your designs with UML
A quick reminder
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 12 / 51
20
18
S1UMLUML (UnifiedModelling
Language) is
currently in
version 2.5.
We will use UML
for class and other
kinds of diagrams
as they come up.
Here’s a diagram
of UML diagrams,
to get all meta.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 13 / 51
20
18
S1. . . and here’s one of classes involved in a Library
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 14 / 51
20
18
S1. . . and here’s one of classes involved in a Library
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 14 / 51
20
18
S1. . . and here’s one of classes involved in a Library
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 14 / 51
20
18
S1. . . and here’s one of classes involved in a Library
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 14 / 51
20
18
S1. . . and here’s one of classes involved in a Library
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 14 / 51
20
18
S1How can I too draw lovely UML diagrams?There are several tools available, in particular those listed onhttp://en.wikipedia.org/wiki/List_of_UML_tools: here are a couple of
open-source, cross-platform ones:
UML Designer: you drag it into Eclipse while it’s running and magic
happens. . . actually that didn’t happen but there is a download that
can be installed in Eclipse.
ArgoUML: quite X-Windows-ey
Violet UML Editor: seems ok but very point-and-click
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 15 / 51
http://marketplace.obeonetwork.com/module/uml
http://argouml.tigris.org/
http://alexdp.free.fr/violetumleditor/page.php
20
18
S1Specifying Object ImplementationsHow shall we implement objects? We use the class, which specifies boththe internal data representation and its operations.
Here’s one now:
Operation1()
type Operation2()
Attribute1
type Attribute2
Class Name Here we specify the name of the
class (in bold) and below it, the
variables/attributes and
operations, each with optional
type declarations.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 16 / 51
20
18
S1VisibilityIn C++ the public, protected and private modifiers are used toconstrain access, and this access cannot be made more open byinheritance. Access can only be restricted further.
UML allows for optional visibility / accessibility tags on each element: +
for public, – for private, # for protected and ∼ (tilde) for package
visibility.
# Operation1()
type Operation2()
+ Attribute1
– type Attribute2
Class Name
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 17 / 51
20
18
S1InstantiationWe use dashed arrows to denote that one class instantiates (makes aninstance of) another:
Instantiator Instantiatee
Objects are created by instantiating a class, and the object is then an
instance of the class.
Classes can have individual data called instance variables and / or shared
data called class variables.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 18 / 51
20
18
S1InheritanceWe use the familiar triangle arrow head for inheritance relationships:
DerivedClass
SuperClass
There are several rules governing how operations and variables that are in
the superclass are inherited by the base class.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 19 / 51
20
18
S1Abstract Classes / InterfacesWe represent classes that cannot be instantiated by showing their name initalics or putting ¿ and À around the name (sometimes both).
Operation1()
Operation2()
≪Abstract Class≫
Operation1()
Operation2()
Concrete Subclass
Abstract class names and
method names are italic;
they may or may not be
overridden in derived
classes.
Concrete classes can have
no abstract methods.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 20 / 51
20
18
S1ImplementationWe use a dashed line with the triangle arrowhead to show implementationrather than the solid line for inheritance:
Operation1()
Attribute1
Interface
Operation1()
Attribute1
Implementing Class
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 21 / 51
20
18
S1Mixin ClassA “mix in” class (or just mixin) is a class that’s designed to addfunctionality to another class. It is not intended to be instantiated, so it isabstract, and it requires multiple inheritance.
MixinOperation()
Mixin
ExistingOperation()
MixinOperation()
AugmentedClass
ExistingOperation()
ExistingClass
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 22 / 51
20
18
S1Class and Interface InheritanceIn Java it’s easy to differentiate between a class and an interface but inC++ (and most other languages) it’s less obvious.An object’s class specifies both the interface and the internal
representation and operations.
An object’s type only specifies the interface.
An object can have many types, and many different classes can have the
same type.
In C++ we can use abstract classes with no method bodies just as we
would use interfaces in Java:
1 class MyInterface
2 {
3 public :
4 virtual void DanceLikeTheresNooneWatching () = 0;
5 }
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 23 / 51
20
18
S1Creational Patterns
Abstracting the Instantiation Process
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 24 / 51
20
18
S1What is a creational pattern?Creational Patterns (CPs) abstract the instantiation process, making asystem independent of how its objects are created, composed and
represented.
Class creational patterns use inheritance to vary the class that’s
instantiated, whereas object creational patterns delegate the instantiation
process to another object.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 25 / 51
20
18
S1What is a creational pattern? (cont.)There are five Creational Patterns (which we will discuss in this course):Abstract Factory Provides an interface to create collections of relatedobjects without specifying their concrete classes: they remain
abstract.
Builder Provides methods to create different representations of
objects by building them with different operations.
Factory Method Defers instantiation to subclasses: useful when a class
can’t know what class of objects to create, and wants its
subclasses to specify the objects it creates.
Singleton Ensures there’s only one instance of the class and gives a
global access point for it. (Some people hate these.)
Prototype Specify a prototypical instance and use that to clone new
instances (with possible further modifications).
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 26 / 51
20
18
S1Creational Pattern
Composite
Façade
Template
Method
Abstract
Factory
Builder
Factory
Method
Prototype
Singleton
creating
composites
often
uses
implement
using
single
instance
single
instance
configure factory
dynamically
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 27 / 51
20
18
S1Topic 6: The Factory Method and theAbstract Factory Design Patterns
Building Objects using Factories
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 28 / 51
20
18
S1The factory method
An interface for creating an object
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 29 / 51
20
18
S1Design Pattern: Factory MethodPurpose/Intent: Design an interface for creating an object, but leave theimplementation decision to concrete classesMotivation: Suppose you have a general application framework (likeOffice) that can create a variety of different applications and
document types. To create a spreadsheet applications we
might define SpreadsheetApp and SpreadsheetDoc; for a
word processing application we’d have WordProcApp and
WordProcDoc. Both use the common framework.
Applicability: Any framework where a set of subclasses have to be created
that are different among concrete implementations
Benefits: Flexibility: subclasses get a hook[1] for providing an
extension to an object; connects parallel class hierarchies
Limitations: Can require subclassing just to get an implementation
See Also: Abstract Factory, Template Method, Prototype
[1]provides default behaviour that can be extended
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 30 / 51
20
18
S1Factory Method StructureProduct
ConcreteProduct
FactoryMethod()
Operation()
Creator
…
product = FactoryMethod()
…
FactoryMethod()
ConcreteCreator …return new
ConcreteProduct
…
Participants
Product: defines the interface of objects the factory method creates;
ConcreteProduct: implements the Product interface;
Creator: declares the factory method and may define a default
implementation that returns a default ConcreteProduct;
ConcreteCreator: overrides the factory method to return an instance of
the ConcreteProduct
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 31 / 51
20
18
S1Two varieties of FactoryVariety 1: the Creator class is concrete: This provides reasonable defaultbehaviours, and enables subclasses to override the defaultbehaviours where required.Variety 2: the Creator class is abstract: This requires subclasses to be
made because there’s no reasonable default value. On the
plus side, this avoids the problem of dealing with
instantiating unforeseeable classes.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 32 / 51
20
18
S1Finally, Factory Method Example – Variety 11 // factoryDemo .h2 # pragma once3 # include
8 virtual std :: string tell () = 0;
9 };
10 class Rectangle : public Shape { // concreteProduct
11 public :
12 virtual std :: string tell () { return ” Rectangle “; }
13 };
14 class Circle : public Shape { // concreteProduct
15 public :
16 virtual std :: string tell () { return ” Circle “; }
17 };
18 class ShapeFactory { // creator / concreteCreator
19 public :
20 virtual Shape * newShape (enum ShapeType type) {
21 switch (type) {
22 case TCirc :
23 return new Circle ();
24 case TRect :
25 return new Rectangle ();
26 default :
27 return nullptr ;
28 }
29 }
30 };
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 33 / 51
20
18
S1Factory Method Example (cont’d)And here is output:1 # include ” factoryDemo .h”2 # include
3 int main () {
4 ShapeFactory factory ;
5 Shape * first = factory . newShape ( TRect );
6 std :: cout << " First shape is a " << first ->tell () << "." << std :: endl;
7 Shape * second = factory . newShape ( TCirc );
8 std :: cout << " Second shape is a " << second ->tell () << "." << std :: endl;
9 delete first ;
10 delete second ;
11 }
~> g++ factoryDemo -o factoryDemo
~> ./factoryDemo
First shape is a Rectangle.
Second shape is a Circle.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 34 / 51
20
18
S1FactoryMethod notesThe Factory method lets a class defer instantiation to subclasses.
This is achieved by defining a separate method for creating the objects.
This method can then be overridden by subclasses to specify the derived
type of product that will be created.
The Factory Method is also known as a Virtual Constructor.
It is commonly used as a tool to implement the Abstract Factory (see next
pattern).
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 35 / 51
20
18
S1Another Factory Method ExampleOpen()Close()Save()Revert()Document
MyDocument
CreateDocument()
NewDocument()
OpenDocument()
Application …
Document* doc = CreateDocument()
docs.Add(doc);
doc->Open()
…
return new MyDocumentCreateDocument()
MyApplication
The Application here is a framework that is subclassed to get a concrete
MyApplication; MyApplication overrides CreateDocument() to create its
own appropriate documents, which have the required Document interface.
Open() and Close() are overridden in MyDocument because they have
their own specific requirements, but Save() and Revert() are complete as
they are.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 36 / 51
20
18
S1The abstract factory
An interface for creating families of related
objects
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 37 / 51
20
18
S1Design Pattern: Abstract FactoryPurpose/Intent: Enable creation of multiple related objects without havingto provide their concrete classesMotivation: Client code should not have to know every detail of how aninterface is implemented
Applicability: Any time you have multiple possible implementations, e.g.,
on different platforms, for things that have the same interface
Benefits: This isolates the concrete classes from the client code and
makes switching between implementations very simple
Limitations: Adding new sets of concrete classes is not necessarily very
simple.
See Also: Singleton, Factory Method, Prototype
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 38 / 51
20
18
S1Structure CreateProductA()CreateProductB()AbstractFactory
CreateProductA()
CreateProductB()
ConcreteFactory1
Client
AbstractProductA
AbstractProductB
ProductA1 ProductA2
ProductB1 ProductB2
CreateProductA()
CreateProductB()
ConcreteFactory2
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 39 / 51
陈启帆�
20
18
S1StructureCreateProductA()CreateProductB()AbstractFactory
CreateProductA()
CreateProductB()
ConcreteFactory1
Client
AbstractProductA
AbstractProductB
ProductA1 ProductA2
ProductB1 ProductB2
CreateProductA()
CreateProductB()
ConcreteFactory2
Participants
AbstractFactory: declares the
interface for operations that
will create abstract product
types;
ConcreteFactory: implements
these operations to create
concrete products;
AbstractProduct: declares the interface for a product object;
ConcreteProduct: defines the product according to the above;
Client: only uses interfaces declared by AbstractFactory and
AbstractProduct.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 40 / 51
20
18
S1Abstract Factory ParticipantsA number of (other) design pattern components are involved inimplementing an Abstract Factory:AbstractFactory declares the interface that a factory must implement inorder to create the right concrete classes;
ConcreteFactory a number of these implement the methods whose
interfaces are defined in the AbstractFactory;
AbstractProduct the interface for a type of product object;
ConcreteProduct the implementation of the above AbstractProduct
interface;
Client uses the AbstractFactory and AbstractProduct interfaces
only, and doesn’t need to be concerned with any Concrete
objects doesn’t need to see the
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 41 / 51
20
18
S1Abstract Factory ExampleYou might use an Abstract Factory when you’re designing a cross-platformapplication, where each platform has its own style or “look-and-feel”: then
there needs to be a concrete implementation for each graphical object that
should be displayed.
The Abstract Factory doesn’t create any instances, it just sets up the
interface a Factory to create them.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 42 / 51
20
18
S1Abstract Factory Example (cont.)CreateScrollBar()CreateMenu()WidgetFactory
CreateScrollBar()
CreateMenu()
phone-WF
CreateScrollBar()
CreateMenu()
PC-WF
Client
Menu
ScrollBar
phone-Menu PC-Menu
phone-ScrollBar PC-ScrollBar
The client only sees the blue
classes, which are abstract.
The Abstract Factory
(“WidgetFactory”) constructs
subclasses of these interfaces
for a given purpose, e.g., a
particular platform.
Here I’ve labelled the “phone”
widgets pink, and the “PC”
widgets light green: note that
the client code doesn’t use
these directly, but only
communicates with them
through their supertype, in
this case the Menu and
ScrollBar interfaces.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 43 / 51
20
18
S1An Abstract Factory Is Good (and bad) Becauseit isolates the concrete classes from the client, enabling them to bedeveloped separately and the client code to be properlyimplementation-agnostic;it makes exchanging concrete product families easy: just call a
different concrete factory when needed;
it promotes consistency: everything has to adhere to the same
abstract interface, so among different (concrete) implementations the
same abstract design can be maintained;
adding new products is difficult: if a new kind of product is added
then it has to be added to each ConcreteFactory.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 44 / 51
20
18
S1Finally, a concrete example1 // productDemo .h2 # pragma once3 # include
8 };
9 class Duck : public Toy { // concreteProductA
10 public :
11 virtual std :: string tell () { return “duck”; }
12 };
13 class Cat : public Toy { // concreteProductA
14 public :
15 virtual std :: string tell () { return “cat”; }
16 };
17 class Colour { // ProductB
18 public :
19 virtual ~ Colour () { }
20 virtual std :: string get () = 0;
21 };
22 class Black : public Colour { // concreteProductB
23 public :
24 virtual std :: string get () { return ” black “; }
25 };
26 class Yellow : public Colour { // concreteProductB
27 public :
28 virtual std :: string get () { return ” yellow “; }
29 };
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 45 / 51
20
18
S1Example (Cont.)1 // abstractFactory .h2 # pragma once3 # include
8 virtual Toy* createToy () = 0;
9 virtual Colour * createColour () = 0;
10 };
11 class DuckFactory : public Factory { // concreteProductA
12 public :
13 virtual Toy* createToy () { return new Duck (); }
14 virtual Colour * createColour () { return new Yellow (); }
15 };
16 class CatFactory : public Factory { // concreteProductA
17 public :
18 virtual Toy* createToy () { return new Cat (); }
19 virtual Colour * createColour () { return new Black (); }
20 };
Toy factories galore! We have different concrete factories producing
specific toys in specific colours.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 46 / 51
20
18
S1Example (Cont.)1 # include
8 Toy *toy = m_factory -> createToy ();
9 Colour * colour = m_factory -> createColour ();
10 std :: cout << "Sell toy " << toy ->tell () << " in " << colour ->get () << std :: endl;
11 delete toy; delete colour ;
12 }
13 };
14 int main () {
15 DuckFactory duckFactory ;
16 Seller duckSeller (& duckFactory );
17 duckSeller . sellToy ();
18 CatFactory catFactory ;
19 Seller catSeller (& catFactory );
20 catSeller . sellToy ();
21 return 0;
22 }
~> g++ abstractFactory.cpp -o abstractFactory
~> ./abstractFactory
Sell toy duck in yellow
Sell toy cat in black
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 47 / 51
20
18
S1Implementation NotesJust a couple of pointers when implementing an Abstract Factory.
The ConcreteProduct creates the, well, the concrete products. These
are usually best implemented using a FactoryMethod.
Use of this pattern makes it possible to interchange concrete
implementations without changing the code that uses them, even at
runtime. However, using this pattern may result in unnecessary
complexity and extra work in implementing this design pattern.
Additionally, higher levels of separation and abstraction can result in
systems which are more difficult to debug and maintain. Therefore, as
with all design patterns it must be applied at the appropriate time.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 48 / 51
dp:FactoryMethod
20
18
S1Comparing the Factory Patterns
Not all factories behave the same
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 49 / 51
20
18
S1Similarities between the factory design patternsBoth design patterns defer initialisation to concrete classes. That is thatthe construction of a set of classes or single classes construction is deferred
to its derived class(es)
The concrete classes are handled using their base classes. That is the
client code only considers the base class (interface). It does not need to be
aware of the specific concrete class definition.
Both allow for new derived types to be introduced with no change to the
code that uses the base class.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 50 / 51
20
18
S1Differences between the factory design patternsThe abstract factory is used to create a family of related dependentobjects without specifying their concrete classes while the factory methoddefines the process to create a single instance of an object without
specifying its concrete class. Therefore, it is possible to implement the
abstract factory design pattern using the factory method design pattern.
But you cannot implement the factory method design pattern using the
abstract factory design pattern.
An application will often only have one abstract factory which creates all
products within an application, while the factory method is used to design
only one specific product, and is therefore often a design pattern which is
reused.
© Drinkwater, Charleston, Scholz (USyd.SIT) INFO3220: Object Oriented Design 2018 S1 51 / 51
Lecture 5: Design Patterns
Design Patterns
Redesign
Creational Patterns
Lecture 6: The Factory Method and the Abstract Factory Design Patterns
The Factory Method
Factory Method
The Abstract Factory
Abstract Factory
Comparing the Factory Patterns