Chapter 3 Integrative Coding
Chapter 3 Integrative Coding
INTEGRATIVE
CODING
1
INTEGRATIVE CODING
2
3
OBJECT-ORIENTED
PROGRAMMING PARADIGM
• Encapsulation, inheritance & polymorphism
• Sub-systems may be created by a composition
of objects
4
ENCAPSULATION
• Information hiding
• Combines private data attributes with public
methods that operate on the data in a class
• Promotes maintainability and reusability
• A client of this class may only view or change
data using the methods provided
5
IMPLEMENTING ENCAPSULATION
• Declare the variables of a class as private
• Provide public setter and getter methods to
modify and view the variables values
6
BENEFITS OF ENCAPSULATION
7
INHERITANCE
• A form of a software reuse
• A new class is created by
– Absorbing 吸收 an existing class’s members
– Embellishing 修饰 them with new or modified
capabilities
8
BENEFITS OF INHERITANCE
• Save development time
• Improve quality
– reuse proven, debugged code
9
IMPLEMENTING
INHERITANCE
Base class Derived class
11
POLYMORPHISM
• “Many forms” - to assign multiple meanings
to the same method name
• A reference variable of a superclass type can
point to an object of its subclass
• Implemented using late binding (dynamic
binding), i.e. the method to be executed is
determined at execution time
12
POLYMORPHIC REFERENCE
VARIABLES
• A reference variable can refer to objects of its
subclasses
class Circle extends Shape { .. }
Shape objRef;
The reference variable objRef can point to any
object of the class Shape or the class Circle
13
BENEFITS OF
POLYMORPHISM
• Promotes reusability of code and provides late
(run-time) binding
14
POLYMORPHISM AND REFERENCES
15
COMPOSITION
• Another way to relate two classes
• One or more members of a class are objects of
another class type
• “has-a” relation between classes
– E.g., “every person has a date of birth”
Example?
16
COMPOSITION EXAMPLE
17
REUSABLE OO DESIGN
• Knowing concepts like encapsulation,
inheritance & polymorphism doesn’t make
one a good OO designer
• Problems faced by inexperienced developers
and designers
– Difficult to spot reusable components
– How to design and implement flexible software so
to maximize reuse
18
PRINCIPLES FOR WRITING
REUSABLE & FLEXIBLE
SOFTWARE
1. Encapsulate what varies 各不相同
2. Program to an interface
3. Favor 赞成 composition over inheritance
19
1. ENCAPSULATE WHAT
VARIES
• Identify the ways in which your software will
change
• Hide the details of what can change behind the
public interface of a class
20
2. PROGRAM TO AN
INTERFACE
• When designing components, choose to
program as an interface instead of an abstract
class, if possible
• Greater degree of polymorphism
21
3. FAVOR COMPOSITION OVER
INHERITANCE
• When designing components, choose
composition instead of inheritance, if possible
22
COMPOSITION vs
INHERITANCE
• Inheritance
• Less flexibility
• Subclasses tightly coupled to the parent classes as the parent
classes define part of representation
• No complete encapsulation of representation
• There’s dependency between the subclass and its superclass
• Composition
• More flexibility
• Loose coupling between subclasses and parent classes
• Encapsulation
• internal implementation of the aggregating class is not visible
(hidden)
23
24
RATIONALE
How to design and implement flexible
software to maximize reuse?
25
DESIGN PATTERNS
• General reusable solution to a commonly
occurring problem
• Proven sound (effective and efficient) software
strategies of designing classes
• They are reusable (i.e., generic), but don’t have
to be implemented in the same way
26
DESIGN PATTERNS DESCRIPTIONS
• They describe
– Design problems that occur repeatedly, and
– Core solutions to those problems
• Pattern description usually make use of object-
oriented characteristics such as inheritance and
polymorphism
27
REUSABLE SOLUTIONS TO
REOCCURING DESIGN PROBLEMS
28
USE OF DESIGN PATTERNS
29
EXAMPLE : GUI PROGRAMMING
Java
C#
30
Each implementation is unique, but in both cases
the design is the same.
31
BENEFITS OF DESIGN PATTERNS
• Facilitate reuse
• Capture expertise; facilitate its dissemination 传播
• Define a shared vocabulary for discussing design
• Demonstrate concepts and principles of good design
– i.e. classes created are reusable and extensible
• Knowing popular design patterns makes it easier to learn class libraries that
use design patterns
32
DESIGN PATTERNS vs
FRAMEWORKS
•Frameworks
• Facilitates reuse
• For an entire system
• Specific implementations
• More instructive
•Design patterns
• Facilitates reuse
• Smaller architectural elements
• More abstract
• More reusable and flexible
33
PATTERN CATEGORIES
35
36
DESCRIBING DESIGN PATTERNS
✧ Pattern name – a short descriptive name
✧ Intent – the design problems/issues the pattern
addresses
✧ Motivation – a scenario illustrating a design problem
& how the design patterns solve the problem
✧ Structure – solution expressed in a graphical
representation of classes in the pattern
✧ Sample Code – a code fragment showing an example
implementation of the pattern
✧ Discussion – some of the implementation issues
associated with the use of the pattern 37
SINGLETON PATTERN 单例模式
OVERVIEW[Cannot apply in assignment]
• A creational pattern
• One of the simplest design patterns
• Involves a single class which is responsible to create an object
while making sure that only single object gets created
• This class provides a way to access its only object which can
be accessed directly without need to instantiate the object of
the class
38
SINGLETON PATTERN
• The Singleton pattern ensures that a class has only one instance
and provides a global point of access to it.
• Design Problem: Sometimes it‘s appropriate to have exactly one
instance of a class 一 个 类 的 一 个 实 例 : window manager, print
spooler 打印后台处理程序 , file system
• Intent
– ensures that not more than one instance of a class is created
– provides a global point of access to this instance.
• Example: You may have a class that represents an interface to a
database. If multiple database connections are expensive or not
supported well by your database you may want all parts of your
program to share the same database connection.
39
40
Example: Database connection Java class implemented as a singleton
public class DatabaseConnection {
private static DatabaseConnection instance = null;
private DatabaseConnection() {
// Establish a database connection ...
}
public synchronized static DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection( );
}
return instance;
}
// Database interface methods
public synchronized String getGrade(String student,
String course, String test) {
...
return ...;
}
}
41
Example: Java Client Class for the Singleton Pattern
public class Client {
public void printTranscript(String student) {
DatabaseConnection db = DatabaseConnection.getInstance();
...
String grade = db.getGrade(student, course, test);
...
}
}
42
Chapter1Example3 NetBeans Project
• Refactor the code in this project such that it
uses the Singleton pattern to encapsulate the
code for database operations.
Refactoring
• to improve internal structure
without changing external
behavior
• the goal is to improve the
quality of existing code
43
OBSERVER PATTERN
• A behavioral pattern
• Used when there is one-to-many relationship between objects
– E.g., if one object is modified, its dependent objects are to
be notified automatically
• Intent – The observer design pattern defines a one-to-many
relationship between a subject object and any number of
observer objects such that when the subject object changes,
observer objects are notified and given a chance to react to
changes in the subject
44
OBSERVER PATTERN EXAMPLE
• Sometimes objects are dependent in a way that a change
in one object will require a change in another
• E.g., in a spreadsheet, data is stored in cells and there can
be multiple views of the data.
45
46
SUBJECT & OBSERVER
• Subject
– the object which will frequently change its state and upon
which other objects depend
• Observer
– the object which depends on a subject and updates according
to its subject's state.
• There is a one-to-many dependency such that when the
subject changes state, all its dependent objects are
notified and updated automatically
• The observer pattern is a.k.a dependence mechanism /
publish-subscribe / broadcast / change-update
47
OBSERVER PATTERN - EXAMPLE
a
6 b
3 c1 b
x 5 3 2
Observers
y 0
8
0
1
0
1 a c
z 0 0 0 a b
0 0 0 c
a =
50%
b =
Subject 30%
c =
20%
requests, modifications
change notification
48
Observer
Source: Holzner
S (2006), Design
Patterns For
Dummies®,
Wiley Publishing,
p. 88
49
Observer (cont’d)
50
Use the Observer pattern when
• An abstraction has two aspects, one dependent on
the other. Encapsulating these aspects in separate
objects lets you vary and reuse them
independently.
• When a change to one object requires changing
others, and you don’t know how many objects
need to be changed.
• When an object should be able to notify other
objects without making assumptions about who
these objects are. In other words, you don’t want
these objects tightly coupled.
51
Source: Gamma E,
Helm R, Johnson R &
Observer
Vlissides J (2009),
Design Patterns:
Elements of Reusable
Object-Oriented
Software, Addison-
Wesley, pp. 294-295.
53
Adapter
54
Target
• Defines the domain-
specific interface
that the client uses
Client
• Collaborates with
Adapter objects conforming
to the Target
interface
Adaptee
• Defines an existing
interface or class
that needs adapting
Adapter
• Adapts the interface
of Adaptee to the
Target interface
58
59
Chapter3 NetBeans Project
Object Adapter
In the adapter folder,
• run ObjectAdapterDemo.php (Shift-F6)
• Draw a class diagram to show the relationships
NameInterface.php WesternName.php
Name.php NameObjectAdapter.php
60
Use the Adapter pattern when
• You want to use an existing class, and its interface does
not match the one you need.
• You want to create a reusable class that cooperates with
unrelated or unforeseen classes, i.e. classes that don’t
necessarily have compatible interfaces.
• (Object adapter only) You need to use several existing
subclasses, but it’s impractical to adapt their interface
by subclassing everyone. An object adapter can adapt
the interface of its parent class.
61
62
DECORATOR PATTERN 装饰器模式
• A structural pattern
• Allows a user to add new functionality to an existing object without altering its
structure
• Attach additional responsibilities to an object dynamically
• Provides a flexible alternative to subclassing for extending functionality
• Creates a decorator class which wraps the original class and provides additional
functionality keeping class methods signature intact 完好无损的 .
63
64
65
66
67
68
69
Decorator
Source:
Gamma et al
(2009), pp.
177-178
71
Use the Decorator pattern
• To add responsibilities to individual objects
dynamically and transparently (i.e. without
affecting other objects)
• For responsibilities that can be withdrawn
• When extension by subclassing is
impractical.
– Sometimes a large number of independent
extensions are possible and would produce an
explosion of subclasses to support every
combination. Or a class definition may be hidden
or otherwise unavailable for subclassing
72
FACADE PATTERN OVERVIEW
• A structural pattern
• Hides the complexities of the system and provides an interface
to the client using which the client can access the system
• Involves a single class which provides simplified methods
required by client and delegates calls to methods of existing
system classes
73
74
FACADE PATTERN
• Intent
– Provide a unified interface to a set of interfaces in a subsystem. Facade
defines a higher-level interface that makes the subsystem easier to use
• Motivation
– Structuring a system into subsystems helps reduce complexity
– A common design goal is to minimize the communication and dependencies
between subsystems.
– Use a facade object to provide a single, simplified interface to the more
general facilities of a subsystem
75
76
77
Facade
78
Chapter3 NetBeans Project
In the facade folder,
• Run FacadeDemo.php (Shift-F6)
• Draw a class diagram to show the relationships
FlightBooker.php
HotelBooker.php
TravelFacade.php
79
Use the Facade pattern when
a. You want to provide a simple interface to a complex
subsystem
b. There are many dependencies between clients and the
implementation classes of an abstraction.
⮚ Introduce a façade to decouple the subsystem from clients
and other subsystems, thereby promoting subsystem
independence and portability
c. You want to layer your subsystems
⮚ Use a façade to define an entry point to each subsystem
level
⮚ If subsystems are dependent, then simplify the dependencies
between them by making them communicate with each
other solely through their facades
80
BENEFITS OF FACADE PATTERN
• Shields clients from subsystem components by
reducing the number of objects that clients have to
deal with
• Promotes loose coupling between the subsystem and
clients
– Loose coupling lets you vary the subsystem component
without affecting its clients
– Principle of Least Knowledge: aim to create loosely coupled
systems of cohesive objects to minimize an object’s class
dependencies
• Does not prevent clients from using subsystem if they
need to
81
COMPILERS: FACADE PATTERN EXAMPLE
• We typically think of a programming language
compiler as a single system
• Many complex systems combine to make a
compiler
– Code divided into tokens by the parser
– Lexigraphical analyzer computes tokens’ meanings
– Analysis improved & simplified by optimizer
– Code generator lowers & outputs result
82
COMPILERS: FACADE PATTERN EXAMPLE
Compiler Invocations
Compile()
Stream
Scanner Token
BytecodeStream
Parser Symbol
CodeGenerator
PnodeBuilder Pnode
StatementNode ExpressionNode
RISCCodegenerator StackMachineCodegenerator
83
APPICATION SERVERS: FACADE
PATTERN EXAMPLE
84
FACTORY METHOD OVERVIEW
• A creational pattern
• One of most used design pattern in Java
• Creates an object without exposing the creation
logic to the client and refer to newly created
object using a common interface
• Define an interface for creating an object, but
let the subclasses decide which class to
instantiate
• Lets a class defer instantiation to subclasses
85
FACTORY METHOD
• Intent
– Defines an interface for creating objects, but let
subclasses decide which class to instantiate
– Refers to the newly created object through a common
interface
• Use when a class
– Can’t predict the class of the objects it needs to create
– Wants its subclasses to specify the objects that it
creates
– Delegates responsibility to one of multiple helper
subclasses, and you need to localize the knowledge of
which helper is the delegate
86
87
ENCAPSULATE CREATION CODE
88
Factory Method
Source: Gamma et al
(2009), pp. 108-109
• Creator
❑ Declares the factory method, which returns an object of type Product.
Creator may also define a default implementation of the factory method
that returns a default ConcreteProduct object.
❑ May call the factory method to create a Product object
❑ConcreteCreator
❑ Overrides the factory method to return an instance of a ConcreteProduct
89
Factory Method Example
91
PROXY PATTERN OVERVIEW
• A structural pattern
• In proxy pattern
– A class represents functionality of another class
– We create object having the original object to
interface its functionality to the outer world
• The Proxy Pattern provides a surrogate or
placeholder for another object to control
access to it by creating a representative object
92
PROXY PATTERN: 3 TYPES
• Remote proxy
• Virtual proxy
• Protection proxy
93
REMOTE PROXY
• Caching of information
• The proxy object is a local representative for
an object in a different address space
• Good if information does not change too often
• E.g., in an ATM implementation, it holds
proxy objects for bank information that exists
in the remote server
94
VIRTUAL PROXY
• Stand-in
• Object is too expensive to create or too
expensive to download
• Good if the real object is not accessed too
often
95
PROTECTION PROXY
• Access control
• The proxy object provides protection for the
real object
• Good when different actors should have
different access and viewing rights for the
same object
– Example: Grade information accessed by
administrators, teachers and students
96
BENEFITS OF PROXY PATTERN
• Remote proxy can hide resident details.
• Virtual proxy creates expensive objects on
demand, rather than all at startup
• Protection proxies can allow housekeeping and
other tasks to be encapsulated
97
Proxy • Subject: defines the
common interface for
RealSubject and
Proxy, so that a
proxy can be used
anywhere a
RealSubject is
expected.
• RealSubject:
defines the real object
that the proxy
represents.
98
Proxy (cont’d)
Source: Gamma et al
(2009), pp. 209-210.
• Proxy:
o Maintains a reference that lets the proxy access the real subject.
o Provides an interface identical to Subject’s so that a proxy can be
substituted for the real subject.
o Controls access to the real subject and may be responsible for
creating and deleting it.
99
Chapter3 NetBeans Project
In the proxy folder,
• Run ProxyDemo.php (Shift-F6)
• Draw a class diagram to show the relationships
Image.php
RealImage.php
ProxyImage.php
100
Use the Proxy pattern as follows:
• A remote proxy provides a local representative for an
object in a different address space
– Remote proxies are responsible for encoding a request
and its arguments and for sending the encoded request to
the real subject in a different address space.
• A virtual proxy creates expensive objects on demand
– Virtual proxies may cache additional information about
the real subject so that they can postpone accessing it.
• A protection proxy controls access to the original
object.
– Protection proxies check that the caller has the access
permissions required to perform a request.
101
STRATEGY DESIGN PATTERN
• A behavioral pattern
• A class behavior or its algorithm can be
changed at run time
• We create objects which represent various
strategies and a context object whose behavior
varies as per its strategy object
• The strategy object changes the executing
algorithm of the context object
102
Strategy Source: Gamma et al (2009), pp. 316-317.
104
Use the Strategy pattern when
• Many related classes differ only in their behavior. Strategies
provide a way to configure a class with one of many
behaviours.
• You need different variants of an algorithm. E.g., you might
define algorithms reflecting different space/time trade-offs.
Strategies can be used when these variants are implemented
as a class hierarchy of algorithms.
• An algorithm uses data that clients shouldn’t know about.
Use the Strategy pattern to avoid exposing complex,
algorithm-specific data structures.
• A class defines many behaviors, and these appear as
multiple conditional statements in its operations. Instead of
many conditionals, move related conditional branches into
their own Strategy class.
105
RECOGNIZING DESIGN PROBLEMS
107