Unit III Software Design

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

UNIT III SOFTWARE DESIGN

Software design – Design process – Design concepts – Coupling – Cohesion – Functional


independence – Design patterns – Model-view-controller – Publish-subscribe – Adapter –
Command – Strategy – Observer – Proxy – Facade – Architectural styles – Layered - Client
Server - Tiered - Pipe and filter- User interface design-Case Study.

1. System Design
 System architecture is the conceptual model that defines the structure, behavior, and
more views of a system. An architecture description is a formal description and
representation of a system, organized in a way that supports reasoning about the
structures and behaviors of the system
 System design is the designing the software/application as a whole [high level]
that may include analysis, modelling, architecture, Components, Infrastructure
etc. whereas the objected-oriented design is the set of defined rules/concepts to
implement the functionalities within a software
 System Design is the process of designing the architecture, components, and interfaces
for a system so that it meets the end-user requirements. Systems design is the process of
defining the architecture, components, modules, interfaces, and data for a system to
satisfy specified requirements. Systems design implies a systematic approach to the design
of a system.
Identify System Scope and Approach:
 System Design may take a bottom-up or top-down approach, which takes into account all
related variables of the system that need to be created from the architecture. These required
hardware and software, right down to the data and how it travels and transforms throughout
its travel through the system.
 A top-down design is the decomposition of a system into smaller parts in order to
comprehend its compositional sub-systems. Every subsystem is refined in greater detail, for
example, sometimes dividing into many different levels of subsystem, so that the whole
specification is decomposed to basic elements. As soon as these base elements are identified,
it is easier to build these elements as computer modules.
 The bottom up design model starts with most specific and basic components. It proceeds
with composing higher level of components by using basic or lower level components. It
keeps creating higher level components until the desired system is not evolved as one single
component. With each higher level, the amount of abstraction is increased. Bottom-up
strategy is more suitable when a system needs to be created from some existing system,
where the basic primitives can be used in the newer system.

. Abstract Design:
Once the scope and approach of system design is finalised then next step is to outline the high
level abstract design. The goal of this is to outline all the important components that your
architecture will need like identify the main components and the connections between them. In
addition to the business requirements of a system, you must satisfy the service-level or quality
of service (QoS) requirements. An architect, is responsible to work with the stakeholders of the
system during the inception and elaboration phases to define a quality of service measurement

1
for each of the service-level requirements. The System architecture must address the following
service-level requirements: performance, scalability, reliability, availability, extensibility,
maintainability, manageability, and security. The Architect has to make trade-offs between these
requirements

Service Level Requirements:

 The performance requirement is usually measured in terms of response time for a given
screen transaction per user. In addition to response time, performance can also be measured
in transaction throughput, which is the number of transactions in a given time period, usually
one second.

 Scalability is the ability to support the required quality of service as the system load
increases without changing the system. A system can be considered scalable if, as the load
increases, the system still responds within the acceptable limits.

 Reliability ensures the integrity and consistency of the application and all its transactions. As
the load increases on your system, your system must continue to process requests and handle
transactions as accurately as it did before the load increased. Reliability can have a negative
impact on scalability.

 Availability ensures that a service/resource is always accessible. Reliability can contribute to


availability, but availability can be achieved even if components fail.

 Extensibility is the ability to add additional functionality or modify existing functionality


without impacting existing system functionality.

 Maintainability is the ability to correct flaws in the existing functionality without impacting
other components of the system.

 Manageability is the ability to manage the system to ensure the continued health of a system
with respect to scalability, reliability, availability, performance, and security.

 Security is the ability to ensure that the system cannot be compromised. Security is by far the
most difficult systemic quality to address. Security includes not only issues of confidentiality
and integrity, but also relates to Denial-of-Service (DoS) attacks that impact availability.

System architecture diagram.

 This diagram gives us the abstract view of the components and their relationship with the
system that makes the system work.
 This is the most basic example of the system architecture diagram and as mentioned it is also
the general representation of the system.

2
Types of System Architecture Diagram

Depending on the types of the system architecture, the system architecture diagram also has some
types that are listed below.
 Software Architecture Diagram
 Hardware Architecture Diagram
 Enterprise Architecture Diagram
 Collaborative Systems Architecture Diagram
 Manufacturing systems Architecture Diagram
 Strategic system architecture diagram

Software architecture:

3
SYSTEM ARCHITECURE:

Example: system architecture includes following ,

 Component diagram
 Deployment diagram
 Package diagram

Component diagram:

ATM:

4
PASSPORT AUTOMATION SYSTEM

Deployment diagram

ATM

Passport automation system

5
Package diagram

 Package diagrams can be defined as structural UML diagrams that show the
organization and arrangement of various UML elements in packages. A package
that is the building block of a package diagram, is a grouping of related model
elements. These model elements can be diagrams, documents, classes, or even
other packages. A package is represented by a file folder symbol in the diagram
with nested elements that can have a hierarchical arrangement.

 Package diagrams reflect the organization of packages in the system and their
elements. In theimplementation phase, packages are translated as namespaces.

Part 2: Purpose and Benefit

 Package diagrams have many applications in various types of systems and


projects. The most common purpose of using package diagrams is an
organization of use case diagrams and class diagrams. They are also used to
provide a visual organization of the layered architecture within any large-scale
software system. Package diagrams also clarify the import and access
dependencies between different elements like packages, classes, and
components.

 The versatility of package diagrams allows us to illustrate both structure and


dependencies between subsystems or modules through these diagrams. These
diagrams also contain packages that have use cases showing the functionality of
a software system. The dependencies betweenthese packages are represented by
labels or stereotypes, indicating the communication mechanism between the
layers.

 Package diagrams are used in large-scale systems to picture dependencies


between significant elements in the design and depict a compile-time grouping
mechanism.

 Package diagrams are handy in software development, especially in object-


oriented projects. They allow encapsulation and the grouping of different
artifacts to make the system easy to understand, execute and maintain. Other
benefits of the package diagram are:

 Package diagrams simplify the class diagrams by grouping similar elements.


This grouping can be done on various grounds, including the domain, type, or
functionalityof the classes or the other artifacts. As a result, packages make the
class diagram look clean and precise while making the implementation more
modular.
 Package diagrams show a clear view of the hierarchical structure of the

6
different elements in a system.
 Package diagrams are a great aid when you need to show only the high-level
view of how a large-scale project is organized.
 Package diagrams support the evolution of a project from a simple design to a
detailed structure. They can start with a broader understanding of the
components needed and eventually evolve to a concrete system.
Part 3: Package Diagram Notations

Here are the essential components you'll find within a package diagram:

Package

The package is a namespace that groups logically related elements together within a system.
This is the building block of any package diagram. Each element that is included in the
package must be package able and have a unique name.

Package able element

What is a package able element? It is a named element that is owned directly by


a package. Package able elements are events, components, use cases, and other
packagesas well.

Dependencies

Dependencies are visual representations of dependability or influence of one


element to the other element or set of components. Dependencies are divided
into two groups.

1. Access dependencies

Access dependencies show that one package requires assistance


from the functions of another package.

2. Import dependencies

Import dependencies show that functionality has been imported from one package
to another

7
Package diagram for ATM:

Package diagram for online shop cart:

Some major elements of the package diagram are shown on the drawing below. Web
Shopping, Mobile Shopping, Phone Shopping, and Mail Shopping packages merge
Shopping Cart package. The same 4 packages use Payment package. Both Payment and
Shopping Cart packages import other packages.

8
PACKAGE DIAGRAM FOR JAVA:

Benefits

 Acts as a blueprint
 Customer wants
 Better relationship between supplier and customer

 For being compliant

9
Difference between System Architecture and Software Architecture

S.No. SYSTEM ARCHITECTURE SOFTWARE ARCHITECTURE


System architecture is a conceptual model
that describes the structure and behavior of Software architecture refers to the
multiple components and subsystems like process of creating high level structure
multiple software applications, network of a software system.
devices, hardware, and even other
01. Machinery of a system.
It focuses on the entire system. Whereas software architecture focuses
02. on the components.
Various types of system architectures are Various software architecture patterns
Hardware architecture, Enterprise include Serverless Architecture, Event
Architecture, Collaborative system Driven Architecture, Micro Service
03. architecture. Architecture.
It helps to define low level infrastructure of It helps to define high level infrastructure
04. a software. of a software.
What we are building overall is system What we are building individually is
05. Architecture. software architecture.
Software architecture considers different
System architecture includes elements of factors such as Business strategy, human
both software and hardware and is used dynamics, quality attributes, design,
06. to enable design of such a composite and
system. IT environment etc.
It defines structure, behavior and view of a It defines the solutions to meet technical
07. system. and business requirements.
So in one line overall view of So in one line individual component
allcomponents and their relationship and its relationship with other is called
08. is called software architecture.
system architecture.
For example software architecture is one
For example system architecture of an component of ordering system is web
order entering system contains web front front end which consist of responsive
end, business layer service, web user interface, view controller, web
09. backend, data services and many more.
base etc.

Software Design Process

The design phase of software development deals with transforming the customer
requirements as described in the SRS documents into a form implementable using a
programming language.

The software design process can be divided into the following three levels of phases of
design:

1. Interface Design

10
2. Architectural Design

3. Detailed Design

Interface Design:
Interface design is the specification of the interaction between a system and
its environment. this phase proceeds at a high level of abstraction with
respect to the inner workings of the system i.e, during interface design, the
internal of the systems are completely ignored and the system is treated as a
black box. Attention is focussed on the dialogue between the target system
and the users, devices, and other systems with which it interacts. The design
problem statement produced during the problem analysis step should identify
the people, other systems, and devices which are collectively called agents.

Interface design should include the following details:


 Precise description of events in the environment, or messages from
agents to which the system must respond.
 Precise description of the events or messages that the system must produce.
 Specification on the data, and the formats of the data coming into
and going out of the system.
 Specification of the ordering and timing relationships between
incoming events or messages, and outgoing events or outputs.
Architectural Design:
Architectural design is the specification of the major components of a
system, their responsibilities, properties, interfaces, and the relationships and
interactions between them. In architectural design, the overall structure of the

11
system is chosen, but the internal details of major components are ignored.
Issues in architectural design include:
 Gross decomposition of the systems into major components.
 Allocation of functional responsibilities to components.
 Component Interfaces
 Component scaling and performance properties, resource
consumption properties, reliability properties, and so forth.
 Communication and interaction between components.
The architectural design adds important details ignored during the interface
design. Design of the internals of the major components is ignored until the
last phase of the design.

Detailed Design:
Design is the specification of the internal elements of all major system
components, their properties, relationships, processing, and often their
algorithms and the data structures.
The detailed design may include:
 Decomposition of major system components into program units.
 Allocation of functional responsibilities to units.
 User interfaces
 Unit states and state changes
 Data and control interaction between units
 Data packaging and implementation, including issues of scope and
visibility of program elements
 Algorithms and data structures
Introduction to design process

 The main aim of design engineering is to generate a model which shows


firmness, delight and commodity.
 Software design is an iterative process through which requirements are
translated into the blueprint for building the software.

Software quality guidelines

 A design is generated using the recognizable architectural styles and


compose a good design characteristic of components and it is
implemented in evolutionary manner for testing.
 A design of the software must be modular i.e the software must be
logically partitioned into elements.
 In design, the representation of data , architecture, interface and components should be distinct.
 A design must carry appropriate data structure and recognizable data patterns.
 Design components must show the independent functional characteristic.

12
 A design creates an interface that reduce the complexity of connections between the
components.
 A design must be derived using the repeatable method.
 The notations should be use in design which can effectively communicates its meaning.

Quality attributes

The attributes of design name as 'FURPS' are as follows:

Functionality:

It evaluates the feature set and capabilities of the program.

Usability:

It is accessed by considering the factors such as human factor, overall


aesthetics, consistency and documentation.

Reliability:

It is evaluated by measuring parameters like frequency and security of failure,


output result accuracy, the mean-time-to-failure(MTTF), recovery from
failure and the the program predictability.

Performance:

It is measured by considering processing speed, response time, resource


consumption, throughput and efficiency.

Supportability:

 It combines the ability to extend the program, adaptability, serviceability.


These three term defines the maintainability.
 Testability, compatibility and configurability are the terms using which a
system can be easily installed and found the problem easily.
 Supportability also consists of more attributes such as compatibility,
extensibility, fault tolerance, modularity, reusability, robustness, security,
portability, scalability.

13
Design concepts

The set of fundamental software design concepts are as follows:

1. Abstraction

 A solution is stated in large terms using the language of the


problem environment at the highest level abstraction.
 The lower level of abstraction provides a more detail description of the solution.

 A sequence of instruction that contain a specific and


limited function refers in a procedural abstraction.
 A collection of data that describes a data object is a data abstraction.
2. Architecture

 The complete structure of the software is known as software architecture.


 Structure provides conceptual integrity for a system in a number of ways.
 The architecture is the structure of program modules where
they interact with each other in a specialized way.
 The components use the structure of data.

 The aim of the software design is to obtain an architectural framework of a


system.
 The more detailed design activities are conducted from the framework.

3. Patterns
A design pattern describes a design structure and that structure solves a
particular design problem in a specified content.

4. Modularity
 Software is separately divided into name and addressable components. Sometime they

are called as modules which integrate to satisfy the problem requirements.


 Modularity is the single attribute of software that permits a program to be managed easily.

5. Information hiding
Modules must be specified and designed so that the information like
algorithm and data presented in a module is not accessible for other
modules not requiring that information.

6. Functional independence

 The functional independence is the concept of separation and related


to the concept of modularity, abstraction and information hiding.

14
 The functional independence is accessed using two criteria i.e Cohesion and coupling.
Cohesion

 Cohesion is an extension of the information hiding concept.


 A cohesive module performs a single task and it requires a small
interaction with the other components in other parts of the program.
Coupling

Coupling is an indication of interconnection between modules in a structure of software.

7. Refinement
 Refinement is a top-down design approach.
 It is a process of elaboration.
 A program is established for refining levels of procedural details.
 A hierarchy is established by decomposing a statement of function in a stepwise
manner till the programming language statement are reached.
8. Refactoring

 It is a reorganization technique which simplifies the design of


components without changing its function behavior.
 Refactoring is the process of changing the software system in a way that it does not
change the
External behaviour of the code still improves its internal structure.

9. Design classes

 The model of software is defined as a set of design classes.


 Every class describes the elements of problem domain and that focus
on features of the problem which are user visible.
Coupling and Cohesion

Module Coupling

In software engineering, the coupling is the degree of interdependence between software


modules. Two modules that are tightly coupled are strongly dependent on each other. However,
two modules that are loosely coupled are not dependent on each other. Uncoupled
modules have no interdependence at all within them.

15
The various types of coupling techniques are shown in fig:

A good design is the one that has low coupling. Coupling is measured by the number of relations
between the modules. That is, the coupling increases as the number of calls between modules
increase or the amount of shared data is large. Thus, it can be said that a design with high
coupling will have more errors.

Types of Module Coupling

16
1. No Direct Coupling: There is no direct coupling between M1 and M2.

In this case, modules are subordinates to different modules. Therefore, no direct coupling.

2. Data Coupling: When data of one module is passed to another module, this is called data
coupling.

3. Stamp Coupling: Two modules are stamp coupled if they communicate using composite data
items such as structure, objects, etc. When the module passes non-global data structure or entire
structure to another module, they are said to be stamp coupled. For example, passing structure
variable in C or object in C++ language to a module.

4. Control Coupling: Control Coupling exists among two modules if data from one module is
used to direct the structure of instruction execution in another.

5. External Coupling: External Coupling arises when two modules share an externally imposed
data format, communication protocols, or device interface. This is related to communication to
external tools and devices.

6. Common Coupling: Two modules are common coupled if they share information through
some global data items.

17
7. Content Coupling: Content Coupling exists among two modules if they share code, e.g., a
branch from one module into another module.

Module Cohesion

In computer programming, cohesion defines to the degree to which the elements of a module
belong together. Thus, cohesion measures the strength of relationships between pieces of
functionality within a given module. For example, in highly cohesive systems, functionality is
strongly related.

Cohesion is an ordinal type of measurement and is generally described as "high cohesion" or


"low cohesion."

18
Types of Modules Cohesion

1. Functional Cohesion: Functional Cohesion is said to exist if the different elements of a


module, cooperate to achieve a single function.
2. Sequential Cohesion: A module is said to possess sequential cohesion if the element of
a module form the components of the sequence, where the output from one component of
the sequence is input to the next.
3. Communicational Cohesion: A module is said to have communicational cohesion, if all
tasks of the module refer to or update the same data structure, e.g., the set of functions
defined on an array or a stack.
4. Procedural Cohesion: A module is said to be procedural cohesion if the set of purpose
of the module are all parts of a procedure in which particular sequence of steps has to be
carried out for achieving a goal, e.g., the algorithm for decoding a message.
5. Temporal Cohesion: When a module includes functions that are associated by the fact
that all the methods must be executed in the same time, the module is said to exhibit
temporal cohesion.
6. Logical Cohesion: A module is said to be logically cohesive if all the elements of the
module perform a similar operation. For example Error handling, data input and data
output, etc.
7. Coincidental Cohesion: A module is said to have coincidental cohesion if it performs a
set of tasks that are associated with each other very loosely, if at all.

19
Differentiate between Coupling and Cohesion

Coupling Cohesion

Coupling is also called Inter-Module Binding. Cohesion is also called Intra-Module


Binding.

Coupling shows the relationships between Cohesion shows the relationship within the
modules. module.

Coupling shows the Cohesion shows the module's


relative independence between the modules. relative functional strength.

While creating, you should aim for low coupling, While creating you should aim for high
i.e., dependency among modules should be less. cohesion, i.e., a cohesive component/
module focuses on a single function (i.e.,
single-mindedness) with little interaction
with other modules of the system.

In coupling, modules are linked to the other In cohesion, the module focuses on a single
modules. thing.

Design Patterns:

GOF Design Patterns

 GOF (Gang of Four) patterns are and how they help solve common problems
encountered in object-oriented design.
 A design pattern is a general reusable solution to a commonly occurring problem
withina given context. What does that mean?
 Programmers often encounter the same problem repeatedly. Rather than have
everyone come up with their own solution to common programming issues, we
use a best practicetype solution that has been documented and proven to work.
 The word general is important. We cannot just copy and paste a design pattern
into our code. A design pattern represents an idea, and we should write an
implementation for that pattern and implement that in our code.

What are Design Patterns?

The design which is used for an older problem is also used to design the solution to a
new problem. Such a common design is known as a pattern of design. The design
pattern is one which is used to design a problem which was extracted from older
problems.

20
Uses:

 Greater help to beginners.


 Code structure easier to understand.
 Guide for individual solution.
 No need to invert new designs.

Design patterns provide solutions to common software design problems. In the case of
object- oriented programming, design patterns are generally aimed at solving the
problems of object generation and interaction, rather than the larger scale problems of
overall software architecture. They give generalised solutions in the form of templates
that may be applied to real-world problems.

Design patterns are a powerful tool for software developers. However, they should not
be seenas prescriptive specifications for software. It is more important to understand the
concepts that design patterns describe, rather than memorising their exact classes,
methods and properties. It
is also important to apply patterns appropriately. Using the incorrect pattern for a
situation or applying a design pattern to a trivial solution can overcomplicate your code
and lead to maintainability issues.

Design patterns, as name suggest, are solutions for most commonly (and frequently)
occurred problems while designing a software. These patterns are mostly “evolved”
rather than “discovered”. A lot of learning, by lots of professional, have been
summarized into these design patterns. None of these patterns force you anything in
regard to implementation; they are just guidelines to solve a particular problem – in a
particular way – in particular contexts. Code implementation is your responsibility.

Who are the Gang of Four?


The Gang of Four are the authors of the book, "Design Patterns: Elements of Reusable
Object- Oriented Software". This important book describes various development
techniques and pitfalls in addition to providing twenty-three object-oriented
programming design patterns. The four authors were Erich Gamma, Richard Helm,
Ralph Johnson and John Vlissides.
Gang of Four Design Patterns
This section gives a high-level description of the twenty-three design patterns described
by the Gang of Four. Each pattern description includes a link to a more detailed article
describing thedesign pattern and including a UML diagram, template source code and a
real-world exampleprogrammed using C#.

21
Pattern classification:

Creational Patterns

The first type of design pattern is the creational pattern. Creational patterns provide ways to
instantiate single objects or groups of related objects. There are five such patterns:

Creational patterns often used in place of direct instantiation with constructors. They make
the creation process more adaptable and dynamic. In particular, they can provide a great
deal of flexibility about which objects are created, how those objects are created, and how
they are initialized.

Design Purpose
Pattern

Name

Builder design pattern is an alternative way to construct complex objects


Builder
and should be used only when we want to build different types of
immutable objects using same object building process.

Prototype design pattern is used in scenarios where application needs to


Prototype
create a large number of instances of a class, which have almost same
state or differ very little.

Factory design pattern is most suitable when complex object creation


Factory
steps are involved. To ensure that these steps are centralized and not
exposed to composing classes.

22
Abstract Abstract factory pattern is used whenever we need another level of
factory abstraction over a group of factories created using factory pattern.

Singleton enables an application to have one and only one instance of a


Singleton class per JVM.

Structural Patterns

The second type of design pattern is the structural pattern. Structural patterns provide a
manner to define relationships between classes or objects.
Structural design patterns show us how to glue different pieces of a system together in a
flexible and extensible fashion. These patterns help us guarantee that when one of the
parts changes, the entire application structure does not need to change.

Design Pattern
Purpose
Name

An adapter convert the interface of a class into another interface


Adapterter clients expect. It lets classes work together that couldn’t otherwise
because of incompatible interfaces.

Bridge design pattern is used to decouple a class into two parts


Bridge – abstraction and it’s implementation – so that both can evolve in
future without affecting each other. It increases the loose coupling
between class abstraction and it’s implementation.

Composite design pattern helps to compose the objects into tree


Composite structures to represent whole-part hierarchies. Composite lets clients
treat individual objects and compositions of objects uniformly.

Decorator design pattern is used to add additional features or


Decorator behaviors to a particular instance of a class, while not modifying the
other instances of same class.

Facade design pattern provide a unified interface to a set of


Facade interfaces in a subsystem. Facade defines a higher-level interface
that makes the subsystem easier to use.

23
Flyweight design pattern enables use sharing of objects to support
Flyweight large numbers of fine-grained objects efficiently. A flyweight is a
shared object that can be used in multiple contexts simultaneously.
The flyweight acts as an independent object in each context.

In proxy design pattern, a proxy object provide a surrogate or


Proxy placeholder for another object to control access to it. Proxy is
heavily used to implement lazy loading related usecases where we
do not want to create full object until it is actually needed.

Behavioural Patterns

 The final type of design pattern is the behavioural pattern. Behavioural patterns
define mannersof communication between classes and objects.
 Behavioral patterns abstract an action we want to take on the object or class that
takes the action. By changing the object or class, we can change the algorithm
used, the objects affected, or the behavior, while still retaining the same basic
interface for client classes.

Design Pattern
Purpose
Name
Chain of responsibility design pattern gives more than one object an
Chain of
opportunity to handle a request by linking receiving objects together in
responsibility
form of a chain.
Command design pattern is useful to abstract the business logic into
discrete actions which we call commands. These command objects
Command help in loose coupling between two classes where one class (invoker)
shall call a method on other class (receiver) to perform a business
operation.
Interpreter pattern specifies how to evaluate sentences in a language,
Interpreter programatically. It helps in building a grammar for a simple language,
so that sentences in the language can be interpreted.
Iterator pattern provides a way to access the elements of an
Iterator
aggregate object sequentially without exposing its underlying
representation.
Mediator pattern defines an object that encapsulates how a set of
Mediator objects interact. Mediator promotes loose coupling by keeping objects
from referring to each other explicitly, and it lets us vary their
interaction independently.
Memento pattern is used to restore state of an object to a previous state.
Memento
It is also known as snapshot pattern.

24
Observer pattern defines a one-to-many dependency between objects
Observer so that when one object changes state, all its dependents are notified
and updated automatically. It is also referred to as the publish-
subscribe pattern.
In state pattern allows an object to alter its behavior when its internal
State state changes. The object will appear to change its class. There shall be
a separate concrete class per possible state of an object.
Strategy pattern is used where we choose a specific implementation of
Strategy algorithm or task in run time – out of multiple other implementations
for same task.
Template method pattern defines the sequential steps to execute a
Template method multi-step algorithm and optionally can provide a default
implementation as well (based on requirements).
Visitor pattern is used when we want a hierarchy of objects to modify
Visitor
their behavior but without modifying their source code.

Design patterns help to translate “OOD (object oriented design) rules”

 Dependency management
 Code reuse
 Ease of planned (and unplanned) changes.
 Maintenance
 Code quality

Structured pattern description:

 Pattern name
 Intent
 Motivation
 Applicability
 Structure
 Participants and collaboration
 Consequences and implementation
 Examples
 Related patterns

Creational classification:

1. Abstract factory method:


 Creates objects without dependence on concrete classes.
 Easy to replace functionality
 Hard to change class structure.

25
2.Prototype:

 Create new objects from a prototype through an interface to avoid


dependency onconcrete classes.
 Easy to get instances for DLLs
 Avoid hierarchy of factories.

Structural patterns:

Adapter: convert the interface of a class to the interface expected by clients.

26
Composite: Composite object recursively into tree-like structure.

Decorator: Add functionality dynamically to the object.

27
Proxy: Provide a placeholder for another object to control access.

Behavioural patterns

Template method: Define invariant algorithm skeleton and defer variant steps to methods in
subclasses.

Chain of responsibility (COR):

Iterator:

Access elements of collection without exposing collection structure.

28
State:
Allow object behaviour change following state change.

Model/View/Controller

What is MVC Design Pattern?

MVC design pattern is also known as Model-View-Controller. It is a common


architectural pattern that is used to design and create interfaces and the structure of an
application. This pattern divides the application into three parts that are dependent and
connected to each other. These designs are used to distinguish the presentation of data
from how the data is accepted from the user to the data shown. These design patterns
have become common in the use of web applications and for developing GUIs.
Understanding MVC Design Pattern

Understanding these Design patterns is easy and simple. The theory stands for Model-
View- Controller Pattern. The functions of the three parts are-

29
1. Model
This part of the design pattern is the primary part and contains application information
purely. It doesn’t contain any information on how to show the data to the user. It is
independent of the user interface. It controls the logic and rules of application.
2. View
This part helps the user to see the model’s data. The main concern of this part is to
access the model’s data. The view section uses a chart, table or diagrams to represent
the information. It can also show similar data and use bar graphs and tables for
different purposes. It is a visualization of information that the application contains.
3. Controller
Most of the work is done by the controller. It provides the support for input and
converts the input to commands for the application. It is used between the model and
view part. The model and the view are interconnected, so the execution is reflected in
the view part.
How does MVC Design Pattern make working so easy?
Today most of applications follow this pattern. It helps in the reusing of code and
parallel development. This makes working easier and simpler. The components
created through the MVC design pattern are independent of each other in nature. This
feature helps the developers to reuse the components and codes easily and quickly in
other multiple applications.
Since the view monitors the data and it is controlled how it is being presented to the
user, the developer can use a similar view with different data for different
applications. This saves a lot of time and effort for the developer.

Top MVC Design Pattern Companies


Some of the Top companies that use MVC Design Pattern are –

o Microsoft, Go Daddy,
o Dell, Visual Studio, Wild Tangent

What can you do with MVC Design Pattern?


They are used commonly by web applications and to design interfaces. Some popular
coding languages such as C#, Python, PHP, and Java work on MVC theory. The
design patterns help in managing the code. The separation of the components of
MVC help to develop reusable codes that are easier to learn. The theory of MVC is
used in UI Toolkits such as Java Swing, Apple’s Cocoa and MFC library.
Working with MVC Design Pattern
MVC is often used in web applications. The view in these applications is the HTML
or XHTML files created by the application.
The controller receives the input in the form of getting input, and it then manages and

30
handles the input to the model. The model contains the data and the rules on the
process of carrying a specific task.The duplication of the model code, which is not of
the higher level, is removed across the different User Interface implementations. The
MVC pattern provides the core of the solution to any issues and helps in adapting
these solutions to each machine.

Advantages
Some of the major pros of using MVC Design Pattern are-

o Multiple views can be made to models

o The partition of duties helps the developer in future developments and upgrades.

o The MVC theory works have low coupling behaviour among the models,
views, andcontrollers.
o Multiple developers can work on models, views, and controllers at the same time.

o The views for a required model are grouped together.

Required Skills
It is an architectural pattern used in web applications. A prior understanding of
programming and web applications will be an advantage to the user. The practice of
coding and scripting and basic knowledge languages such as Python, Java or C# will
give a boost to the learners
And developers. MVC is not a complete application, and it usually requires a service
layer, data access layer or logic layer.
Why should we use the MVC Design Pattern?
 The most important use of it is to segregate the views from the model and controllers.
It helps in separating the display and the data and allow modification in each data
without affecting the others. It is mostly used for developing Graphical User Interface.
 MVC has been widely used for web applications in major programs. Some frameworks
such as JavaScript MVC, Ember JS, and Backbone support the process of MVC partly
on the client.
Scope
The scope of this is bright and demanding. Almost all the top companies and
industries based on websites use MVC design patterns for developing User Interfaces
and models.
Implementation: MVC

We are going to create a Student object acting as a model. Student View will be a view class
which can print student details on console and Student Controller is the controller class
responsible to store data in Student object and update view Student View accordingly.

31
MVC Pattern Demo, our demo class, will use Student Controller to demonstrate use of MVC
pattern.

Step 1

Create Model.

Student.java

public class Student {


private String rollNo;
private String name;

public String getRollNo() {


return rollNo;

public void setRollNo(String rollNo) {


this.rollNo = rollNo;

public String getName() {


return name;

Step 2

32
Create View.

StudentView.java

public class StudentView {

public void printStudentDetails(String studentName, String


studentRollNo){System.out.println("Student: ");

System.out.println("Name: " + studentName);


System.out.println("Roll No: " +
studentRollNo);

Step 3

Create Controller.

StudentController.java

public class StudentController {


private Student model;
private StudentView view;

public StudentController(Student model, StudentView


view){ this.model = model;

this.view = view;

public void setStudentName(String name){


model.setName(name);

public String getStudentName(){


return model.getName();

public void setStudentRollNo(String rollNo){


model.setRollNo(rollNo);

33
public String getStudentRollNo(){
return model.getRollNo();

public void updateView(){

view.printStudentDetails(model.getName(), model.getRollNo());

Step 4

Use the Student Controller methods to demonstrate MVC design pattern usage.

MVCPatternDemo.java

public class MVCPatternDemo {

public static void main(String[] args) {

//fetch student record based on his roll no from the


databaseStudent model = retriveStudentFromDatabase();

//Create a view : to write student details on


console StudentView view = new StudentView();

StudentController controller = new StudentController(model,


view);controller.updateView();

//update model data


controller.setStudentName("John");

controller.updateView();

private static Student


retriveStudentFromDatabase(){ Student student =
new Student(); student.setName("Robert");
student.setRollNo("10");

return student;

34
}

Step 5

Verify the output.

Student:

Name: Robert Roll No: 10 Student:

Name: John Roll No: 10

Publish-subscribe pattern
In object-oriented software engineering (OOSE), the publish-subscribe pattern is a behavioral
design pattern that allows a group of objects to communicate with each other in a loosely
coupled manner. This pattern is often used to implement distributed event handling systems. In a
publish-subscribe system, objects (subscribers) subscribe to receive notifications (or events)
from a central entity (publisher) without having direct knowledge of each other.

Here's how the publish-subscribe pattern works in the context of OOSE:

Publisher:

The publisher is responsible for broadcasting events or messages to all interested subscribers.

It maintains a list of subscribers that have expressed interest in receiving specific types of events.

Subscriber:

Subscribers are objects that want to be notified when a particular event of interest occurs.

They subscribe to specific types of events with the publisher.

Event:

An event represents a message or notification that the publisher sends to its subscribers.

Events can carry data related to the occurrence, and subscribers can respond accordingly.

Loose Coupling:

Subscribers are not directly aware of the existence of other subscribers or the publisher.

This loose coupling allows for a more modular and maintainable system since objects are not
tightly bound to each other.

35
Example:

Consider a graphical user interface (GUI) framework where various components (buttons, text
fields, etc.) may be interested in receiving notifications about mouse clicks.

The GUI framework acts as the publisher, and the components act as subscribers subscribing to
mouse-click events.

When a user clicks the mouse, the framework publishes a mouse-click event, and all subscribed
components receive notifications.

UML Diagram:

In the UML diagram above:

The Publisher class has a method subscribe (Subscriber) for allowing objects to subscribe to
events.

The Subscriber interface declares the method update (Event) that concrete subscribers must
implement to handle incoming events.

Concrete classes (Concrete Publisher and Concrete Subscriber) provide specific


implementations.

The publish-subscribe pattern enhances flexibility and scalability in systems where different
components need to react to events without tight dependencies. This promotes a more modular
and maintainable design in object-oriented systems

Adapter Pattern

An Adapter Pattern says that just "converts the interface of a class into another interface that
a client wants".

In other words, to provide the interface according to client requirement while using the services
of a class with a different interface.

The Adapter Pattern is also known as Wrapper.

Advantage of Adapter Pattern


o It allows two or more previously incompatible objects to interact.
o It allows reusability of existing functionality.

Usage of Adapter pattern:

It is used:

o When an object needs to utilize an existing class with an incompatible interface.

36
o When you want to create a reusable class that cooperates with classes which don't have
compatible interfaces.
o When you want to create a reusable class that cooperates with classes which don't have
compatible interfaces.

Example of Adapter Pattern

Let's understand the example of adapter design pattern by the above UML diagram.

UML for Adapter Pattern:

There are the following specifications for the adapter pattern:

o Target Interface: This is the desired interface class which will be used by the clients.
o Adapter class: This class is a wrapper class which implements the desired target
interface and modifies the specific request available from the Adaptee class.
o Adaptee class: This is the class which is used by the Adapter class to reuse the existing
functionality and modify them for desired use.
o Client: This class will interact with the Adapter class.

Implementation of above UML:

Step 1

Create a Credit Card interface (Target interface).

1. public interface CreditCard {


2. public void giveBankDetails();
3. public String getCreditCard();
4. }// End of the CreditCard interface.

37
Step 2

Create a Bank Details class (Adaptee class).

File: BankDetails.java

// This is the adapter class.


public class BankDetails{
private String bankName;
private String accHolderName;
private long accNumber;

public String getBankName() {


return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getAccHolderName() {
return accHolderName;
}
public void setAccHolderName(String accHolderName) {
this.accHolderName = accHolderName;
}
public long getAccNumber() {
return accNumber;
}
public void setAccNumber(long accNumber) {
this.accNumber = accNumber;
}
}// End of the BankDetails class.

Step 3

Create a Bank Customer class (Adapter class).

File: BankCustomer.java

// This is the adapter class

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BankCustomer extends BankDetails implements CreditCard {
public void giveBankDetails(){
try{

38
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the account holder name :");


String customername=br.readLine();
System.out.print("\n");

System.out.print("Enter the account number:");


long accno=Long.parseLong(br.readLine());
System.out.print("\n");

System.out.print("Enter the bank name :");


String bankname=br.readLine();

setAccHolderName(customername);
setAccNumber(accno);
setBankName(bankname);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public String getCreditCard() {
long accno=getAccNumber();
String accholdername=getAccHolderName();
String bname=getBankName();

return ("The Account number "+accno+" of "+accholdername+" in "+bname+ "


bank is valid and authenticated for issuing the credit card. ");
}
}//End of the BankCustomer class.

Step 4

Create a Adapter PatternDemo class (client class).

File: AdapterPatternDemo.java

//This is the client class.


public class AdapterPatternDemo {
public static void main(String args[]){
CreditCard targetInterface=new BankCustomer();
targetInterface.giveBankDetails();
System.out.print(targetInterface.getCreditCard());
}
}//End of the BankCustomer class.

39
Output
Enter the account holder name :Sonoo Jaiswal

Enter the account number:10001

Enter the bank name :State Bank of India

The Account number 10001 of Sonoo Jaiswal in State Bank of India bank is valid
and authenticated for issuing the credit card.

Command Pattern
A Command Pattern says that “encapsulates a request under an object as a command and passes
it to invoker object. Invoker object looks for the appropriate object which can handle this
command and pass the command to the corresponding object and that object executes the
command".

It is also known as Action or Transaction.

Advantage of command pattern

 It separates the object that invokes the operation from the object that actually performs
the operation.
 It makes easy to add new commands, because existing classes remain unchanged.
Usage of command pattern:

It is used:

 When you need parameterize objects according to an action perform.


 When you need to create and execute requests at different times.
 When you need to support rollback, logging or transaction functionality.
Example of command pattern

Let's understand the example of adapter design pattern by the above UML diagram.

UML for command pattern:

These are the following participants of the Command Design pattern:

Command: This is an interface for executing an operation.

Concrete Command: This class extends the Command interface and implements the execute
method. This class creates a binding between the action and the receiver.

40
Client: This class creates the ConcreteCommand class and associates it with the receiver.

Invoker: This class asks the command to carry out the request.

Receiver: This class knows to perform the operation.

Implementation of above UML:

Step 1

Create a ActionListernerCommand interface that will act as a Command.

public interface ActionListenerCommand {

public void execute();

Step 2

Create a Document class that will act as a Receiver.

File: Document.java

public class Document {

public void open(){

System.out.println("Document Opened");

public void save(){

System.out.println("Document Saved");

Step 3

Create a Action Open class that will act as an Concrete Command.

File: ActionOpen.java

public class ActionOpen implements ActionListenerCommand{

private Document doc;

public ActionOpen(Document doc) {

this.doc = doc;

41
}

@Override

public void execute() {

doc.open();

Step 4

Create a ActionSave class that will act as an ConcreteCommand.

File: AdapterPatternDemo.java

public class ActionSave implements ActionListenerCommand{

private Document doc;

public ActionSave(Document doc) {

this.doc = doc;

@Override

public void execute() {

doc.save();

Step 5

Create a MenuOptions class that will act as an Invoker.

File: ActionSave.java

public class ActionSave implements ActionListenerCommand{

private Document doc;

public ActionSave(Document doc) {

this.doc = doc;

42
@Override

Public void execute() {

doc.save();

Step 6

Create a CommanPatternClient class that will act as a Client.

File: AdapterPatternDemo.java

public class CommandPatternClient {

public static void main(String[] args) {

Document doc = new Document();

ActionListenerCommand clickOpen = new ActionOpen(doc);

ActionListenerCommand clickSave = new ActionSave(doc);

MenuOptions menu = new MenuOptions(clickOpen, clickSave);

menu.clickOpen();

menu.clickSave();

Output

Document Opened

Document Saved

Strategy Pattern

A Strategy Pattern says that "defines a family of functionality, encapsulate each one, and make
them interchangeable".

The Strategy Pattern is also known as Policy.

Benefits:

43
o It provides a substitute to subclassing.
o It defines each behavior within its own class, eliminating the need for conditional
statements.
o It makes it easier to extend and incorporate new behavior without changing the
application.

Usage:
o When the multiple classes differ only in their behaviors.e.g. Servlet API.
o It is used when you need different variations of an algorithm.

Strategy Pattern in (Core Java API's) or JSE 7 API's:

Strategy Pattern in (Advance Java API's) or JEE 7 API's:

UML for Strategy Pattern:

Implementation of Strategy Pattern:

Step 1:

Create a Strategy interface.

//This is an interface.

44
public interface Strategy {

public float calculation(float a, float b);

}// End of the Strategy interface.

Step 2:

Create a Addition class that will implement Startegy interface.

//This is a class.
public class Addition implements Strategy{

@Override
public float calculation(float a, float b) {
return a+b;
}

}// End of the Addition class.

Step 3:

Create a Subtraction class that will implement Startegy interface.

//This is a class.
public class Subtraction implements Strategy{

@Override
public float calculation(float a, float b) {
return a-b;
}
}// End of the Subtraction class.

Step 4:

Create a Multiplication class that will implement Startegy interface.

//This is a class.
public class Multiplication implements Strategy{
@Override
public float calculation(float a, float b){
return a*b;
}
}// End of the Multiplication class.

45
Step 5:

Create a Context class that will ask from Startegy interface to execute the type of strategy.

//This is a class.
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public float executeStrategy(float num1, float num2){
return strategy.calculation(num1, num2);
}
}// End of the Context class.

Step 6:

Create a StartegyPatternDemo class.

//This is a class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StrategyPatternDemo {

public static void main(String[] args) throws NumberFormatException, IOException {

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


System.out.print("Enter the first value: ");
float value1=Float.parseFloat(br.readLine());
System.out.print("Enter the second value: ");
float value2=Float.parseFloat(br.readLine());
Context context = new Context(new Addition());
System.out.println("Addition = " + context.executeStrategy(value1, value2));

context = new Context(new Subtraction());


System.out.println("Subtraction = " + context.executeStrategy(value1, value2));

context = new Context(new Multiplication());


System.out.println("Multiplication = " + context.executeStrategy(value1, value2));
}

}// End of the StrategyPatternDemo class.

46
Output:

Observer Pattern

An Observer Pattern says that "just define a one-to-one dependency so that when one object
changes state, all its dependents are notified and updated automatically".

The observer pattern is also known as Dependents or Publish-Subscribe.

Benefits:

o It describes the coupling between the objects and the observer.


o It provides the support for broadcast-type communication.

Usage:

o When the change of a state in one object must be reflected in another object without
keeping the objects tight coupled.
o When the framework we writes and needs to be enhanced in future with new observers
with minimal changes.

47
UML for Observer Pattern:

Implementation of Observer Pattern

Step 1:

Create a ResponseHandler1 class the will implement the java.util.Observer interface.

//This is a class.
import java.util.Observable;
import java.util.Observer;
public class ResponseHandler1 implements Observer {
private String resp;
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
resp = (String) arg;
System.out.println("\nReceived Response: " + resp );
}
}
}// End of the ResponseHandler1 interface.

Step 2:

Create a ResponseHandler2 class the will implement the java.util.Observer interface.

48
//This is a class.
import java.util.Observable;
import java.util.Observer;
public class ResponseHandler2 implements Observer {
private String resp;
public void update(Observable obj, Object arg) {
if (arg instanceof String) {
resp = (String) arg;
System.out.println("\nReceived Response: " + resp );
}
}
}// End of the ResponseHandler2 interface.

Step 3:

Create an EventSource class that will extend the java.util.Observable class .

//This is a class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;

public class EventSource extends Observable implements Runnable {


@Override
public void run() {
try {
final InputStreamReader isr = new InputStreamReader(System.in);
final BufferedReader br = new BufferedReader(isr);
while (true) {
String response = br.readLine();
setChanged();
notifyObservers(response);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}// End of the Eventsource class.

49
Output:

Proxy Pattern

Simply, proxy means an object representing another object.

According to GoF, a Proxy Pattern "provides the control for accessing the original object".

So, we can perform many operations like hiding the information of original object, on demand
loading etc.

Proxy pattern is also known as Surrogate or Placeholder.

Advantage of Proxy Pattern


o It provides the protection to the original object from the outside world.

Usage of Proxy Pattern:

It is used:

o It can be used in Virtual Proxy scenario---Consider a situation where there is multiple


database call to extract huge size image. Since this is an expensive operation so here we

50
can use the proxy pattern which would create multiple proxies and point to the huge size
memory consuming object for further processing. The real object gets created only when
a client first requests/accesses the object and after that we can just refer to the proxy to
reuse the object. This avoids duplication of the object and hence saving memory.
o It can be used in Protective Proxy scenario---It acts as an authorization layer to verify
that whether the actual user has access the appropriate content or not. For example, a
proxy server which provides restriction on internet access in office. Only the websites
and contents which are valid will be allowed and the remaining ones will be blocked.
o It can be used in Remote Proxy scenario---A remote proxy can be thought about the stub
in the RPC call. The remote proxy provides a local representation of the object which is
present in the different address location. Another example can be providing interface for
remote resources such as web service or REST resources.
o It can be used in Smart Proxy scenario---A smart proxy provides additional layer of
security by interposing specific actions when the object is accessed. For example, to
check whether the real object is locked or not before accessing it so that no other objects
can change it.

Example of Proxy Pattern

Let's understand the example of proxy design pattern by the above UML diagram.

UML for Proxy Pattern:

Implementation of above UML:

Step 1

Create an OfficeInternetAccess interface.

public interface OfficeInternetAccess {


public void grantInternetAccess();
}

51
Step 2

Create a Real Internet Access class that will implement Office Internet Access interface for
granting the permission to the specific employee.

File: RealInternetAccess.java

public class RealInternetAccess implements OfficeInternetAccess {


private String employeeName;
public RealInternetAccess(String empName) {
this.employeeName = empName;
}
@Override
public void grantInternetAccess() {
System.out.println("Internet Access granted for employee: "+ employeeName);
}
}

Step 3

Create a Proxy Internet Access class that will implement Office Internet Access interface for
providing the object of Real Internet Access class.

File: ProxyInternetAccess.java

public class ProxyInternetAccess implements OfficeInternetAccess {


private String employeeName;
private RealInternetAccess realaccess;
public ProxyInternetAccess(String employeeName) {
this.employeeName = employeeName;
}
@Override
public void grantInternetAccess()
{
if (getRole(employeeName) > 4)
{
realaccess = new RealInternetAccess(employeeName);
realaccess.grantInternetAccess();
}
else
{
System.out.println("No Internet access granted. Your job level is below 5");
}
}
public int getRole(String emplName) {

52
// Check role from the database based on Name and designation
// return job level or job designation.
return 9;
}
}

Step 4

Now, Create a Proxy Pattern Client class that can access the internet actually.

File: ProxyPatternClient.java

public class ProxyPatternClient {


public static void main(String[] args)
{
OfficeInternetAccess access = new ProxyInternetAccess("Ashwani Rajput");
access.grantInternetAccess();
}
}

Facade Pattern

A Facade Pattern says that just "just provide a unified and simplified interface to a set of
interfaces in a subsystem, therefore it hides the complexities of the subsystem from the
client".

In other words, Facade Pattern describes a higher-level interface that makes the sub-system
easier to use.

Practically, every Abstract Factory is a type of Facade.

Advantage of Facade Pattern


o It shields the clients from the complexities of the sub-system components.
o It promotes loose coupling between subsystems and its clients.

Usage of Facade Pattern:

It is used:

o When you want to provide simple interface to a complex sub-system.


o When several dependencies exist between clients and the implementation classes of an
abstraction.

53
Example of Facade Pattern

Let's understand the example of facade design pattern by the above UML diagram.

UML for Facade Pattern:

Implementation of above UML:

Step 1

Create a Mobile Shop interface.

File: MobileShop.java

public interface MobileShop {


public void modelNo();
public void price();
}

Step 2

Create a Iphone implementation class that will implement Mobileshop interface.

File: Iphone.java

public class Iphone implements MobileShop {


@Override
public void modelNo() {
System.out.println(" Iphone 6 ");
}
@Override
public void price() {
System.out.println(" Rs 65000.00 ");

54
}
}

Step 3

Create a Samsung implementation class that will implement Mobileshop interface.

File: Samsung.java

public class Samsung implements MobileShop {


@Override
public void modelNo() {
System.out.println(" Samsung galaxy tab 3 ");
}
@Override
public void price() {
System.out.println(" Rs 45000.00 ");
}
}

Step 4

Create a Blackberry implementation class that will implement Mobileshop interface .

File: Blackberry.java

public class Blackberry implements MobileShop {


@Override
public void modelNo() {
System.out.println(" Blackberry Z10 ");
}
@Override
public void price() {
System.out.println(" Rs 55000.00 ");
}
}

Step 5

Create a ShopKeeper concrete class that will use MobileShop interface.

File: ShopKeeper.java

public class ShopKeeper {


private MobileShop iphone;
private MobileShop samsung;
private MobileShop blackberry;

55
public ShopKeeper(){
iphone= new Iphone();
samsung=new Samsung();
blackberry=new Blackberry();
}
public void iphoneSale(){
iphone.modelNo();
iphone.price();
}
public void samsungSale(){
samsung.modelNo();
samsung.price();
}
public void blackberrySale(){
blackberry.modelNo();
blackberry.price();
}
}

Step 6

Now, Creating a client that can purchase the mobiles from Mobile Shop through Shopkeeper.

File: FacadePatternClient.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FacadePatternClient {
private static int choice;
public static void main(String args[]) throws NumberFormatException, IOException{
do{
System.out.print("========= Mobile Shop ============ \n");
System.out.print(" 1. IPHONE. \n");
System.out.print(" 2. SAMSUNG. \n");
System.out.print(" 3. BLACKBERRY. \n");
System.out.print(" 4. Exit. \n");
System.out.print("Enter your choice: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
choice=Integer.parseInt(br.readLine());
ShopKeeper sk=new ShopKeeper();
switch (choice) {
case 1:
{

56
sk.iphoneSale();
}
break;
case 2:
{
sk.samsungSale();
}
break;
case 3:
{
sk.blackberrySale();
}
break;
default:
{
System.out.println("Nothing You purchased");
}
return;
}

}while(choice!=4);
}
}

Output

========= Mobile Shop ============

1. IPHONE.

2. SAMSUNG.

3. BLACKBERRY.

4. Exit.

Enter your choice: 1

IPhone 6

Rs 65000.00

========= Mobile Shop ============

1. IPHONE.

2. SAMSUNG.

57
3. BLACKBERRY.

4. Exit.

Enter your choice: 2

Samsung galaxy tab 3

Rs 45000.00

========= Mobile Shop ============

1. IPHONE.

2. SAMSUNG.

3. BLACKBERRY.

4. Exit.

Enter your choice: 3

Blackberry Z10

Rs 55000.00

========= Mobile Shop ============

1. IPHONE.

2. SAMSUNG.

3. BLACKBERRY.

4. Exit.

Enter your choice: 4

Nothing you purchased

Architectural Styles
The architecture of a system describes its major components, their relationships (structures), and
how they interact with each other. Software architecture serves as a blueprint for a system. It
provides an abstraction to manage the system complexity. Now we will look at the main
architectural styles:

 Pipe and Filter


 Data-Centered
 Layered

58
 Client-Server
First let's give a description of:

Components - calculation elements and elements for data storage. Communication with other
elements is implemented through their interfaces (ports).

Connectors - the architectural elements for communication. Like the components communicate
with other elements through their interfaces (roles).

Topology - Successful communication between 2 architectural the element occurs when a role is
attached to a port and their interfaces are compatible. The architectural elements, their
interrelationships and limitations, represent the topology.

Pipe and Filter


Definition

Pipe and Filter is architectural pattern, which has independent entities:

 filters (components) - which perform transformations on data and process the input they
receive
 pipes (connectors) - which serve as connectors for the stream of data being transformed,
each connected to the next component in the pipeline.
Description

The pattern of interaction in the pipe-and-filter pattern is haracterized by successive


transformations of streams of data. As you can see in the diagram, the data flows in one
direction. It starts at a data source, arrives at a filter’s input port(s) where processing is done at
the component, and then, is passed via its output port(s) through a pipe to the next filter, and
then eventually ends at the data target.

59
When used

Commonly used in data-processing applications (both batch and transaction-based) where inputs
are processed in separate stages to generate related outputs.

Examples

The architectural pattern is very popular and used in many systems, such as the text-based
utilities in the UNIX operating system. Whenever different data sets need to be manipulated in
different ways, you should consider using the pipe and filter architecture.

 Compilers: They perform language transformation. Input is in language e.g. Java and
output is in machine language. In order to do that the input goes through various stages
inside the compiler — these stages form the pipeline. The most commonly used division
consists of 3 stages: front-end, middle-end, and back-end. The front-end is responsible
for parsing the input language and performing syntax and semantic and then transforms it
into an intermediate language. The middle-end takes the intermediate representation and
usually performs several optimization steps on it, the resulting transformed program in is
passed to the back-end which transforms it into language B. Each level consists of
several steps as well, and everything together forms the pipeline of the compiler.

 UNIX Shell: The Pipeline is one of the defining features of the UNIX shell, and
obviously, the same goes for Linux, MacOS, and any other Unix-based or inspired

60
systems. In a nutshell, it allows you to tie the output of one program to the input of
another. The benefit it brings is that you don’t have to save the results of one program
before you can start processing it with another. The long-term and even more important
benefit is that it encourages programs to be small and simple. There is no need for every
program to include a word-counter if they can all be piped into wc. Similarly, no
program needs to offer its own built-in pattern matching facilities, as it can be piped into
grep. In the provided example, the input.txt is read and the output is then provided to
grep as input which searches for the pattern “text” and then passes the results to sort,
which sorts the results and outputs into the file, output.txt.

cat input.txt | grep "text" | sort > output.txt

input.txt ➜grep ➜sort ➜output.txt

ATM system

Advantages

 Easy and simple for composition and evolution


 Intuitive and easy to understand
 The filters are discrete: reusability and low coupling between components (modifiability)
 Concurrency support
Disadvantages

 Each filter must analyse its data


 Difficult to share global data
 Problems with reuse - e.g. functional transformations with incompatible data
 The data transmission format must be agreed
 Does not provide a way for filters to interact together to solve a problem

61
Data-centered
Definition

The Data-Centered architecture consists of various components that communicate through a


shared data warehouse. The data is centralized and all components can access/modify it. Shared
data can be considered as a connector between components.

Description

In this style we have:

 Central data structure or data warehouse, which is responsible for ensuring permanent
storage data. It represents the current state.
 Many independent components that work with the central data warehouse, perform
calculations, and can return results. Interactions or communication between components
are carried out only through the data warehouse (can be considered as a connector). Data
is the only means of communication between customers. The flow of control
differentiates architecture into two categories: Repository and Blackboard.
Repository:

 The central data structure is passive and customers (components) of the data warehouse
are active.
 Participating components check the repository of data for changes.

62
 No notifications are sent to the components.

Blackboard:

 The central data structure is active and the customers and is passive.
 The logic flow is determined by the current state of data in the data warehouse.
 All components must be informed about changes in the data.
Examples

Databases - The most well-known examples of the data-centered architecture is a database


architecture, in which the common database schema is created with data definition protocol – for
example, a set of related tables with fields and data types in an RDBMS.

Airline CRM System - CRM is a software system that manages personalized relationships with
a company’s clients. Marketing campaigns, customer service, and cross-selling campaigns are
usually managed with a CRM system.

Web-based data services - Another example of data-centered architectures is the web


architecture which has a common data schema (i.e. meta-structure of the Web) and follows
hypermedia data model and processes communicate through the use of shared web-based data
services.

IDE

Advantages

 Scalability - new components can be added


 Concurrency - all components can work in parallel
 Reuse - components are not direct communication with each other
 Centralized data management

63
 Better conditions for security, archiving, etc.
 The components are independent of the manufacturer data
Disadvantages

 High dependence between the data structure of storage and components


 Storage - single point of failure (single point of failure)
 Changes in data structure strongly affect customers
 Multiple sync issues components

Layered
Definition

Organizes the system into layers with related functionality between each layer. Each layer offers
services through an interface, but only for the layer which is directly above it and uses the
services of the layer that is directly below it.

Thus, each layer represents:

• Server - for the top layer

• Client - for the bottom layer

Description

Organizes the system into layers, with related functionality associated with each layer. A layer
provides services to the layer above it, so the lowest level layers represent core services that are
likely to be used throughout the system.

64
Examples

iLearn system - iLearn digital learning system has a four-layer architecture that follows this
pattern.

Open System Interconnection model - OSI model is a reference model and used for
communicating with systems that are open for communication with other systems.

Other 4-layered systems - The presentation layer contains all categories related to the
presentation layer. The business layer contains business logic. The persistence layer is used for
handling functions like object-relational mapping. The database layer is where all the data is
stored.

65
Layered architecture - example app

When used

 Used when building new facilities on top of existing systems, when the development is
spread across several teams with each team responsibility for a layer of functionality or
when
 There is a requirement for multilevel security.

Advantages

 Each layer supports similar tasks (better cohesion)


 Abstraction - the internal structure of the layers is hidden
 Allows replacement of entire layers
 Additional services (e.g. authentication) can be provided in each layer to increase system
reliability
Disadvantages

 Providing a clear separation between layers is often difficult - a high-level layer has to
interact directly with a lower level
 Productivity can be a problem due to multiple levels of interpretation of service request
as it is processed by everyone layer
Client-Server

Definition

At Client-Server the functionality of the system is organized in services provided by servers.


Customers are users of these services and access servers to take advantage of them. It is not
necessary for a server to have information about its .

66
Description

In client–server architecture, the system is presented as a set of services, with each service
delivered by a separate server. Clients are users of these services and access servers to make
Use of them.

Examples

 E-commerce shop
 Client-Server Architecture for a film library

 Other common systems

67
When used

Used when data in a shared database has to be accessed from a range of locations. Because
servers can be replicated, may also be used when the load on a system is variable.

Advantages

 Its centralized architecture facilitates the protection of the data


 Servers can be distributed over a network
 Data is transferred through protocols that are not of interest from the platforms
 General functionality (e.g. printer) can be available to all customers
 The capacity of the Client and the Servers may change separately
Disadvantages

 Productivity depends on the network as well as the system


 If too many customers simultaneously request data from the server may be overloaded
 Data packets can be changed during transmission.
 There may be management problems if the servers are owned by various organizations

User Interface Design

The visual part of a computer application or operating system through which a client interacts
with a computer or software. It determines how commands are given to the computer or the
program and how data is displayed on the screen.

Types of User Interface

There are two main types of User Interface:

 Text-Based User Interface or Command Line Interface


 Graphical User Interface (GUI)

Text-Based User Interface: This method relies primarily on the keyboard. A typical example of
this is UNIX.

Advantages

 Many and easier to customizations options.


 Typically capable of more important tasks.
Disadvantages

 Relies heavily on recall rather than recognition.


 Navigation is often more difficult.

68
Graphical User Interface (GUI): GUI relies much more heavily on the mouse. A typical
example of this type of interface is any versions of the Windows operating systems.

GUI Characteristics

Characteristics Descriptions

Windows Multiple windows allow different information to be displayed


simultaneously on the user's screen.

Icons Icons different types of information. On some systems, icons represent files.
On other icons describes processes.

Menus Commands are selected from a menu rather than typed in a command
language.

Pointing A pointing device such as a mouse is used for selecting choices from a
menu or indicating items of interests in a window.

Graphics Graphics elements can be mixed with text or the same display.

Advantages

 Less expert knowledge is required to use it.


 Easier to Navigate and can look through folders quickly in a guess and check manner.
 The user may switch quickly from one task to another and can interact with several
different applications.
Disadvantages

 Typically decreased options.


 Usually less customizable. Not easy to use one button for tons of different variations.

69
UI Design Principles

User Interface Design

Structure: Design should organize the user interface purposefully, in the meaningful and usual
based on precise, consistent models that are apparent and recognizable to users, putting related
things together and separating unrelated things, differentiating dissimilar things and making
similar things resemble one another. The structure principle is concerned with overall user
interface architecture.

Simplicity: The design should make the simple, common task easy, communicating clearly and
directly in the user's language, and providing good shortcuts that are meaningfully related to
longer procedures.

Visibility: The design should make all required options and materials for a given function
visible without distracting the user with extraneous or redundant data.

Feedback: The design should keep users informed of actions or interpretation, changes of state
or condition, and bugs or exceptions that are relevant and of interest to the user through clear,
concise, and unambiguous language familiar to users.

Tolerance: The design should be flexible and tolerant, decreasing the cost of errors and misuse
by allowing undoing and redoing while also preventing bugs wherever possible by tolerating
varied inputs and sequences and by interpreting all reasonable actions.

70

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy