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 Composition
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
• Design patterns are often systematically
documented for all software developers to use
o Applying design patterns is like reusing experience
o Develop new software without reinventing new solution
strategies
• Design patterns speed up the development
process and ensures coherently integrated and
architected application systems
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
35
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
36
SINGLETON PATTERN OVERVIEW
• 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
37
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. 38
39
40
Example: Database connection Java class implemented as a singleton
41
Example: Java Client Class for the Singleton Pattern
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
Observers
x 5 3 2
y 0
8
0
1
0
1 a c
z 0 0 0
a b c
0 0 0
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.
55
56
• In a food ordering system, the Observer
Pattern can be applied to handle notifications
and updates when the status of an order
changes
57
● Customer Maintenance Module
○ This module is responsible for managing customer data, such as
updating personal information.
○ When customer data changes......
● Notification Module:
○ Sends email notifications to customers when their account information
is updated or when they place an order.
● Statistics Module:
○ Tracks and updates statistics related to customer demographics, order
frequency, and purchasing trends.
● Logging Module:
○ Logs customer activities and changes for auditing and debugging
purposes.
● Recommendation Module:
○ Adjusts product recommendations based on changes to customer
preferences or behavior.
58
E-Learning System
● suggest where we can apply observer pattern
for e-learning system
○ notify students (Observers) about updates or
changes in a course (Subject).
○ students be notified when new assignments are
posted or when their grades are updated
59
60
Adapter
61
62
63
Target
• Defines the
domain-specific
interface that the
client uses
Client
Adapter • Collaborates with
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
65
Chapter3 NetBeans Project
Object Adapter
In the adapter folder,
• run [Link] (Shift-F6)
• Draw a class diagram to show the relationships
[Link] [Link]
[Link] [Link]
• Review and discuss the code with a friend
66
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.
67
The Adapter Design Pattern is useful in scenarios where you
have:-
68
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. 69
70
• Suppose we are developing a billing
software for the dominos. Customers can
order their favorite pizza with extra toppings
on it.
• We have different types of base, a variety of
toppings that add up to the actual cost of
the pizza. How can we build such kind of
system such that it requires minimal
modification, yet we can add new
functionality in the future?
71
Method 1
• Create a class for Pizza and each type of
pizza inheriting the base class.
• Each type of pizza is a sub class of Pizza.
It makes design simple to add new types
of pizzas offered in the future.
72
73
74
Method 2
• Rather than adding various combinations,
why not have instance variables for
toppings in the Pizza class and let the
sub-class inherit them.
75
76
Decorator
Source:
Gamma et al
(2009), pp.
177-178
79
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
80
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
81
82
83
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
84
85
86
Facade
• Subsystem classes
❑ Implement subsystem functionality
❑ Handle work assigned by Facade the object
❑ Have no knowledge of the façade (i.e. they keep no references to it)
87
Chapter3 NetBeans Project
In the facade folder,
• Run [Link] (Shift-F6)
• Draw a class diagram to show the relationships
[Link]
[Link]
[Link]
88
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
89
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
90
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
91
COMPILERS: FACADE PATTERN EXAMPLE
Compiler Invocations
Compile()
Stream
Scanner Token
BytecodeStream
Parser Symbol
CodeGenerator
PnodeBuilder Pnode
StatementNode ExpressionNode
RISCCodegenerator StackMachineCodegenerator
92
APPICATION SERVERS: FACADE
PATTERN EXAMPLE
93
94
95
96
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
97
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
98
99
ENCAPSULATE CREATION CODE
• A simple way to encapsulate this code is to put
it in a separate class
– That new class depends on the concrete classes, but
those dependencies no longer impact the
preparation code
100
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
101
Factory Method Example
103
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
104
105
PROXY PATTERN: 3 TYPES
• Remote proxy
• Virtual proxy
• Protection proxy
106
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
107
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
108
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
109
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
110
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.
111
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.
112
Chapter3 NetBeans Project
In the proxy folder,
• Run [Link] (Shift-F6)
• Draw a class diagram to show the relationships
[Link]
[Link]
[Link]
113
114
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.
115
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
116
Strategy Source: Gamma et al (2009), pp. 316-317.
117
Strategy Example (Refer to Chapter3\strategy folder)
118
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.
119
State Design Pattern
• A behavioral software design pattern
• Allows an object to alter its behavior when
its internal state changes.
120
121
122
RECOGNIZING DESIGN PROBLEMS
▪ Tell several objects that the state of some other object
has changed (Observer pattern)
▪ Tidy up the interfaces to a number of related objects
that have often been developed incrementally
(Facade pattern)
▪ Provide a standard way of accessing the elements in a
collection, irrespective of how that collection is
implemented (Iterator pattern)
▪ Allow for the possibility of extending the functionality
of an existing class at run-time (Decorator pattern)
123
• [Link]
• [Link]
ns
124
• You are developing a logging system for an
application. The application needs a single,
consistent logging service that all components
use. This service should create a single log file
and ensure that all log entries are written
sequentially to this file.
125
• You are tasked with integrating a legacy
payment processing system with a new
e-commerce platform. The legacy system has a
different interface than the one used by the
new platform. You need to ensure that the new
platform can communicate with the legacy
system without modifying its existing codebase.
126
• You are building a home automation system
that integrates multiple subsystems such as
lighting, heating, security, and entertainment.
Each subsystem has its own complex API. You
want to provide a simple interface to users to
control these subsystems without exposing the
complexities of each subsystem.
127
• You are developing a text editor application
that allows users to add features like
spell-checking, grammar-checking, and text
formatting. These features should be optional
and can be combined in various ways. For
instance, a user might want only spell-checking,
or both spell-checking and grammar-checking.
128
• You are designing a stock market application
that tracks stock prices. Multiple modules, such
as a user interface module and an alerting
module, need to be notified whenever a stock
price changes. The stock price updates
frequently, and all dependent modules should
be updated automatically.
129
• You are developing a distributed caching system
for a web application. The application runs on
multiple servers, and each server needs to access
and update a centralized configuration file that
determines caching policies (e.g., TTL, eviction
policies). This configuration should always remain
consistent across all servers, and there should be a
single, synchronized point of access to read and
update the configuration file.
130
• You are developing a multimedia streaming service
that offers different subscription tiers. Each tier
provides additional features like offline downloads, HD
streaming, and multiple device support. These features
should be applied dynamically based on the user’s
subscription level. For instance, a basic subscription
might only support SD streaming, while a premium
subscription supports all features. Users can upgrade
or downgrade their subscriptions at any time, and the
service should adapt accordingly without significant
code changes.
131
• You are integrating a new CRM system into an
existing enterprise software suite. The existing
software suite has several modules (e.g., sales,
customer support, marketing) that interact with the
old CRM system through a defined API. The new
CRM system has a completely different API. You
need to ensure that all modules of the existing
software suite can interact seamlessly with the new
CRM system without changing their code.
132
133