Unit III Software Design
Unit III Software Design
Unit III Software Design
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
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.
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.
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:
Component diagram
Deployment diagram
Package diagram
Component diagram:
ATM:
4
PASSPORT AUTOMATION SYSTEM
Deployment diagram
ATM
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.
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.
Dependencies
1. Access dependencies
2. Import dependencies
Import dependencies show that functionality has been imported from one package
to another
7
Package diagram for ATM:
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
9
Difference between System Architecture and Software Architecture
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.
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
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
Functionality:
Usability:
Reliability:
Performance:
Supportability:
13
Design concepts
1. Abstraction
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
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
14
The functional independence is accessed using two criteria i.e Cohesion and coupling.
Cohesion
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
9. Design classes
Module Coupling
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.
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.
18
Types of Modules Cohesion
19
Differentiate between Coupling and Cohesion
Coupling Cohesion
Coupling shows the relationships between Cohesion shows the relationship within the
modules. module.
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 (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.
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:
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.
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
22
Abstract Abstract factory pattern is used whenever we need another level of
factory abstraction over a group of factories created using factory pattern.
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
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.
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.
Dependency management
Code reuse
Ease of planned (and unplanned) changes.
Maintenance
Code quality
Pattern name
Intent
Motivation
Applicability
Structure
Participants and collaboration
Consequences and implementation
Examples
Related patterns
Creational classification:
25
2.Prototype:
Structural patterns:
26
Composite: Composite object recursively into tree-like structure.
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.
Iterator:
28
State:
Allow object behaviour change following state change.
Model/View/Controller
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.
o Microsoft, Go Daddy,
o Dell, Visual Studio, Wild Tangent
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 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.
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
Step 2
32
Create View.
StudentView.java
Step 3
Create Controller.
StudentController.java
this.view = view;
33
public String getStudentRollNo(){
return model.getRollNo();
view.printStudentDetails(model.getName(), model.getRollNo());
Step 4
Use the Student Controller methods to demonstrate MVC design pattern usage.
MVCPatternDemo.java
controller.updateView();
return student;
34
}
Step 5
Student:
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.
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.
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:
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.
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.
It is used:
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.
Let's understand the example of adapter design pattern by the above UML diagram.
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.
Step 1
37
Step 2
File: BankDetails.java
Step 3
File: BankCustomer.java
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));
setAccHolderName(customername);
setAccNumber(accno);
setBankName(bankname);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public String getCreditCard() {
long accno=getAccNumber();
String accholdername=getAccHolderName();
String bname=getBankName();
Step 4
File: AdapterPatternDemo.java
39
Output
Enter the account holder name :Sonoo Jaiswal
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 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:
Let's understand the example of adapter design pattern by the above UML diagram.
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.
Step 1
Step 2
File: Document.java
System.out.println("Document Opened");
System.out.println("Document Saved");
Step 3
File: ActionOpen.java
this.doc = doc;
41
}
@Override
doc.open();
Step 4
File: AdapterPatternDemo.java
this.doc = doc;
@Override
doc.save();
Step 5
File: ActionSave.java
this.doc = doc;
42
@Override
doc.save();
Step 6
File: AdapterPatternDemo.java
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".
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.
Step 1:
//This is an interface.
44
public interface Strategy {
Step 2:
//This is a class.
public class Addition implements Strategy{
@Override
public float calculation(float a, float b) {
return a+b;
}
Step 3:
//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:
//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:
//This is a class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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".
Benefits:
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:
Step 1:
//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:
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:
//This is a class.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;
49
Output:
Proxy Pattern
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.
It is used:
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.
Let's understand the example of proxy design pattern by the above UML diagram.
Step 1
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
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
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
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.
It is used:
53
Example of Facade Pattern
Let's understand the example of facade design pattern by the above UML diagram.
Step 1
File: MobileShop.java
Step 2
File: Iphone.java
54
}
}
Step 3
File: Samsung.java
Step 4
File: Blackberry.java
Step 5
File: ShopKeeper.java
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
1. IPHONE.
2. SAMSUNG.
3. BLACKBERRY.
4. Exit.
IPhone 6
Rs 65000.00
1. IPHONE.
2. SAMSUNG.
57
3. BLACKBERRY.
4. Exit.
Rs 45000.00
1. IPHONE.
2. SAMSUNG.
3. BLACKBERRY.
4. Exit.
Blackberry Z10
Rs 55000.00
1. IPHONE.
2. SAMSUNG.
3. BLACKBERRY.
4. Exit.
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:
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.
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
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.
ATM system
Advantages
61
Data-centered
Definition
Description
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
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.
IDE
Advantages
63
Better conditions for security, archiving, etc.
The components are independent of the manufacturer data
Disadvantages
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.
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
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
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
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
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.
Text-Based User Interface: This method relies primarily on the keyboard. A typical example of
this is UNIX.
Advantages
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
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
69
UI Design Principles
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