21CS741 SADP Module 1-5 Q&A
21CS741 SADP Module 1-5 Q&A
ans: Each pattern describes a problem which occurs over and over again in our environment,
and then describes the core of the solution to that problem, in such a way that you can use
this solution a million times over, without ever doing it the same way twice.
Essential elements:
The pattern name is a handle we can use to describe a design problem, its solutions, and
consequences in a word or two. Naming a pattern immediately increases our design
vocabulary. It lets us design at a higher level of abstraction. It makes it easier to think about
designs and to communicate them and their trade-offs to others. Finding good names has
been one of the hardest parts of developing our catalog.
The problem describes when to apply the pattern. It explains the problem and its context. It
might describe specific design problems such as how to represent algorithms as objects. It
might describe class or object structures that are symptomatic of an inflexible design.
Sometimes the problem will include a list of conditions that must be met before it makes
sense to apply the pattern.
The solution describes the elements that make up the design, their relationships,
responsibilities, and collaborations. The solution doesn't describe a particular concrete
design or implementation, because a pattern is like a template that can be applied in many
different situations. Instead, the pattern provides an abstract description of a design problem
and how a general arrangement of elements (classes and objects in our case) solves it.
The consequences are the results and trade-offs of applying the pattern. The consequences
for software often concern space and time trade-offs. They may address language and
implementation issues as well. Since reuse is often a factor in object- oriented design, the
consequences of a pattern include its impact on a system's flexibility, extensibility, or
portability.
ans:
1.Abstract Factory: Provide an interface for creating families of related or dependent objects
without specifying their concrete classes.
2.Adapter: Convert the interface of a class into another interface clients expect. Adapter lets
classes work together that couldn't otherwise because of incompatible interfaces.
3.Bridge: Decouple an abstraction from its implementation so that the two can vary
independently.
4.Builder: Separate the construction of a complex object from its representation so that the
same construction process can create different representations.
5.Chain of Responsibility: Avoid coupling the sender of a request to its receiver by giving
more than one object a chance to handle the request. Chain the receiving objects and pass
the request along the chain until an object handles it.
6.Command Encapsulate a request as an object, thereby letting you parameterize clients with
different requests, queue or log requests, and support undoable operations.
10.Factory Method Define an interface for creating an object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation to subclasses.
12.Interpreter Given a language, define a represention for its grammar along with an
interpreter that uses the representation to interpret sentences in the language.
13.Iterator Provide a way to access the elements of an aggregate object sequentially without
exposing its underlying representation.
14.Mediator Define an object that encapsulates how a set of objects interact. Mediator
promotes loose coupling by keeping objects from referring to each other explicitly, and it lets
you vary their interaction independently.
16.Observer Define a one-to-many dependency between objects so that when one object
changes state, all its dependents are notified and updated automatically.
17.Prototype Specify the kinds of objects to create using a prototypical instance, and create
new objects by copying this prototype.
18.Proxy Provide a surrogate or placeholder for another object to control access to it.
19.Singleton Ensure a class only has one instance, and provide a global point of access to it.
20.State Allow an object to alter its behavior when its internal state changes. The object will
appear to change its class.
21.Strategy Define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Design patterns vary in their granularity and level of abstraction. Because there are many
design patterns, we need a way to organize them.
The first criterion, called purpose, reflects what a pattern does. Patterns can be creational,
structural, or behavioral purpose. Creational patterns concern the process of object
creation. Structural patterns deal with the composition of classes or objects. Behavioral
patterns characterize the ways in which classes or objects interact and distribute
responsibility.
The second criterion, called scope, specifies whether the pattern applies primarily to
classes or to objects. Class patterns deal with relationships between classes and their
subclasses. These relationships are established through inheritance, so they are static—
fixed at compile-time.
Object patterns deal with object relationships, which can be changed at run-time and are
more dynamic. Almost all patterns use inheritance to some extent. So the only patterns
labeled "class patterns" are those that focus on class relationships. Note that most
patterns are in the Object scope.
Creational class patterns defer some part of object creation to subclasses, while
Creational object patterns defer it to another object. The Structural class patterns use
inheritance to compose classes, while the Structural object patterns describe ways to
assemble objects.
The Behavioral class patterns use inheritance to describe algorithms and flow of control,
whereas the Behavioral object patterns describe how a group of objects cooperate to
perform a task that no single object can carry out alone.
ans:
1. Design patterns are more abstract than frameworks. Frameworks can be embodied in
code, but only examples of patterns can be embodied in code. A strength of frameworks is
that they can be written down in programming languages and not only studied but executed
and reused directly. In contrast, the design patterns in this book have to be implemented
each time they're used. Design patterns also explain the intent, trade-offs, and consequences
of a design
2. Design patterns are smaller architectural elements than frameworks. A typical framework
contains several design patterns, but the reverse is never true.
3. Design patterns are less specialized than frameworks. Frameworks always have a
particular application domain. A graphical editor framework might be used in a factory
simulation, but it won't be mistaken for a simulation framework. In contrast, the design
patterns in this catalog can be used in nearly any kind of application. While more specialized
design patterns than ours are certainly possible (say, design patterns for distributed systems
or concurrent programming), even these wouldn't dictate an application architecture like a
framework would.
ans:
1. Consider how design patterns solve design problems. discusses how design patterns help
you find appropriate objects, determine object granularity, specify object interfaces, and
several other ways in which design patterns solve design problems. Referring to these
discussions can help guide your search for the right pattern.
2. Scan Intent sections lists the Intent sections from all the patterns in the catalog. Read
through each pattern's intent to find one or more that sound relevant to your problem.
3. Study how patterns interrelate. Shows relationships between design patterns graphically.
Studying these relationships can help direct you to the right pattern or group of patterns.
4. Study patterns of like purpose. The catalog has three chapters, one for creational patterns,
and another for patterns, and a third for behavioral patterns. Each chapter starts off with
introductory comments on the patterns and concludes with a section that compares and
contrasts them. These sections give you insight into the similarities and differences between
patterns of like purpose.
5. Examine a cause of redesign. Look at the causes of redesign starting to see if your problem
involves one or more of them. Then look at the patterns that help you avoid the causes of
redesign.
6. Consider what should be variable in your design. This approach is the opposite of focusing
on the causes of redesign. Instead of considering what might force a change to a design,
consider what you want to be able to change without redesign. The focus here is on
encapsulating the concept that varies a theme of many design patterns.
ans:The last major step in the analysis phase involves the determination of the conceptual
classes and the establishment of their relationships. For example, in the library system, some
of the major conceptual classes include members and books. Members borrow books, which
establish a relationship between them.
Design facilitation: the design stage must determine how to implement the functionality.
For this, the designers should be in a position to determine the classes that need to be
defined, the objects to be created, and how the objects interact. This is better facilitated
if the analysis phase classifies the entities in the application and determines their
relationships.
Added knowledge: The use cases do not completely specify the system. Some of these
missing details can be filled in by the class diagram.
Error reduction: In carrying out this step, the analysts are forced to look at the system
more carefully. The result can be shown to the client who can verify its correctness.
Useful documentation: The classes and relationships provide a quick introduction to the
system for someone who wants to learn it. Such people include personnel who join the
project to carry out the design or implementation or subsequent maintenance of the
system.
ans:
Use case analysis is a case-based way of describing the uses of the system with the goal
of defining and documenting the system requirements. It is essentially a narrative
describing the sequence of events (actions) of an external agent (actor) using the system
to complete a process. It is a powerful technique that describes the kind of functionality
that a user expects from the system. Use cases have two or more parties: agents who
interact with the system and the system itself.
In our simple library system, the members do not use the system directly. Instead, they
get services via the library staff. We assume that some kind of a user-interface is required,
so that when the system is started, it provides a menu with the following choices:
1.Add a member
2. Add books
3. Issue books
4. Return books
5. Remove books
6. Place a hold on a book
7. Remove a hold on a book
8. Process Holds: Find the first member who has a hold on a book
9. Renew books
10. Print out a member‘s transactions
11. Store data on disk
12. Retrieve data from disk
13. Exit
The actors in our system are members of the library staff who manage the daily
operations. This idea is depicted in the use case diagram in Fig. 6.1, which gives an
overview of the system‘s usage requirements.
Use case for returning books: Users return books by leaving them on a library clerk‘s
desk; the clerk enters the book ids one by one to return them. Table 6.6 gives the details
of the use case.
Use cases for removing (deleting) books: printing member transactions, placing a hold,
and removing a hold The next four use cases deal with the scenarios for removing books.
Use case for renewing books: This use case (see Table 6.12) deals with situations where a
user has several books checked out and would like to renew some of these
Module 2
1. Define structural pattern. Explain in detail adapter design pattern. (10 Marks)
ans:Structural patterns are concerned with how classes and objects are composed to form
larger structures.
Motivation:
Sometimes a toolkit class that's designed for reuse isn't reusable only because its
interface doesn't match the domain-specific interface an application requires.
Consider for example a drawing editor that lets users draw and arrange graphical
elements (lines, polygons, text, etc.) into pictures and diagrams.
The drawing editor's key abstraction is the graphical object, which has an editable shape
and can draw itself.
The interface for graphical objects is defined by an abstract class called Shape. The
editor defines a subclass of Shape for each kind of graphical object: a LineShape class for
lines, a PolygonShape class for polygons, and so forth.
Classes for elementary geometric shapes like LineShape and PolygonShape are rather
easy to implement.
Applicability:
• you want to use an existing class, and its interface does not match the one you need.
• you want to create a reusable class that cooperates with unrelated or unforeseen classes,
that is, classes that don't necessarily have compatible interfaces.
• (object adapter only) you need to use several existing subclasses, but it's unpractical to
adapt their interface by subclassing every one. An object adapter can adapt the interface of
its parent class
Participants:
ans:
Motivation:
use decorator:
to add resposilities to individual objects dynamically and transparently, that is, without
affecting other objects.
for responsibilities that can be withdrawn.
when extension by subclassing is impractical. Sometimes a large number of independent
extensions are possible and would produce an explosion of subclasses to support every
combination.
Participants:
• Component (VisualComponent) - defines the interface for objects that can have
responsibilities added to them dynamically.
ans:
motivation:
Structuring a system into subsystems helps reduce complexity. A common design goal is
to minimize the communication and dependencies between subsystems.
One way to achieve this go al is to introduce a facade object that provides a single,
simplified interface to the more general facilities of a subsystem.
Applicability:
Use the Façade pattern when :
• you want to provide a simple interface to a complex subsystem
• there are many dependencies between clients and the implementation classes of an
abstraction.
• you want to layer your subsystems.
Participants:
• Facade (Compiler)
- have no knowledge of the facade; that is, they keep no references to it.
ans:
Motivation:
Consider a document editor that can embed graphical objects in a document. Some
graphical objects, like large raster images, can be expensive to create.
But opening a document should be fast, so we should avoid creating all the expensive
objects at once when the document is opened.
This isn't necessary anyway, because not all of these objects will be visible in the
document at the same time.
The image proxy creates the real image only when the document editor asks it to display
itself by invoking its Draw operation. The proxy forwards subsequent requests directly to
the image. It must therefore keep a reference to the image after creating it
Applicability:
1. A remote proxy provides a local representative for an object in a different address space
4. A smart reference is a replacement for a bare pointer that performs additional actions
when an object is accessed.
Participants:
• Proxy (ImageProxy)
- provides an interface identical to Subject's so that a proxy can by substituted for the real
subject.
- controls access to the real subject and may be responsible for creating and deleting it.
ans:
MOtivation:
Graphics applications like drawing editors and schematic capture systems let users build
complex diagrams out of simple components.
The user can group components to form larger components, which in turn can be
grouped to form still larger components.
A simple implementation could define classes for graphical primitives such as Text and
Lines plus other classes that act as containers for these primitives.
The key to the Composite pattern is an abstract class that represents both primitives and
their containers. For the graphics system, this class is Graphic.
Graphic declares operations like Draw that are specific to graphical objects. It also
declares operations that all composite objects share, such as operations for accessing
and managing its children.
Applicabiliy:
Structure:
• Component (Graphic) - declares the interface for objects in the composition. - Implements
default behavior for the interface common to all classes, as appropriate. - declares an
interface for accessing and managing its child components. - (optional) defines an interface
for accessing a component's parent in the recursive structure, and implements it if that's
appropriate.
• Leaf (Rectangle, Line, Text, etc.) - represents leaf objects in the composition. A leaf has no
children. - defines behavior for primitive objects in the composition.
ans:
Intent: Avoid coupling the sender of a request to its receiver by giving more than one object a
chance to handle the request.
Motivation:
Consider a context-sensitive help facility for a graphical user interface. The user can
obtain help information on any part of the interface just by clicking on it.
The help that's provided depends on the part of the interface that's selected and its
context.
For example, a button widget in a dialog box might have different help information than a
similar button in the main window.
If no specific help information exists for that part of the interface, then the help system
should display a more general help message about the immediate context the dialog box
as a whole.
The idea of this pattern is to decouple senders and receivers by giving multiple objects a
chance to handle a request.
The request gets passed along a chain of objects until one of them handles it.
Applicability:
• more than one object may handle a request, and the handler isn't known a priori. The
handler should be ascertainedautomatically. \
• the set of objects that can handle a request should be specified dynamically.
Participants:
• Handler (HelpHandler)
- canaccessitssuccessor.
- if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request
to its successor.
• Client
ans:Behavioral patterns are concerned with algorithms and the assignment of responsibilities
between objects. Behavioral patterns describe not just patterns of objects or classes but also
the patterns of communication between them.
Sometimes it's necessary to issue requests to objects without knowing anything about
the operation being requested or the receiver of the request.
For example, user interface toolkits include objects like buttons and menus that carry out
a request in response to user input.
But the toolkit can't implement the request explicitly in the button or menu, because
only applications that use the toolkit know what should be done on which object.
As toolkit designers we have no way of knowing the receiver of the request or the
operations that will carry it out.
The Command pattern lets toolkit objects make requests of unspecified application
objects by turning the request itself into an object.
This object can be stored and passed around like other objects. The key to this pattern is
an abstract Command class, which declares an interface for executing operations.
• Receiver (Document, Application) - knows how to perform the operations associated with
carrying out a request. Any class may serve as a Receiver.
ans:
If a particular kind of problem occurs often enough, then it might beworthwhileto express
instances of the problem as sentences in a simple language.
Then you can build an interpreter that solves theproblem by interpreting these
sentences.
For example, searching for strings that match a pattern is a common problem.
Regular expressions are a standard language for specifying patterns of strings.
Rather than building custom algorithms to match each pattern against strings, search
algorithms could interpret a regular expression that specifies a set of strings to match.
Applicability:
Use the Interpreter pattern when there is a language to interpret, and you can represent
statements in the language as abstract syntax trees.
Participants:
• AbstractExpression (RegularExpression)
- one such classisrequired for every rule R ::= R\R^ ••.Rn in the grammar.
- maintains instance variables of type AbstractExpression for each of the symbols RI through
Rn.
• Context
• Client
- builds (oris given) an abstract syntax tree representing a particular sentence in the language
that the grammar defines.
ans:
Motivation:
An aggregate object such as a list should give you a way to access its elements without
exposing its internal structure.
Moreover, you might want to traverse the list in different ways, depending on what you
want to accomplish.
The key idea in this pattern is to take the responsibility for access and traversal out of the
list object and put it into an iterator object.
We define an AbstractList class that provides a common interfacefor manipulating lists.
Similarly, we need an abstract Iteratorclass that defines a common iteration interface.
Applicability: Use the Iterator pattern
• to provide a uniform interface for traversing different aggregate structures (that is, to
support polymorphic iteration).
Participants:
Implimentation:
1. Who controls the iteration? A fundamental issue is deciding which party controls the
iteration, the iterator or the client that uses the iterator. When the client controls the
iteration, the iterator is called an external iterator, and when the iterator controls it, the
iterator is an internal iterator.
2. External iterators are more flexible than internal iterators. It's easy to compare two
collections for equality with an external iterator, for example, but it's practically impossible
with internaliterators. Internal iterators are especially weak in a language likeC++ that does
not provide anonymous functions, closures, orcontinuations like Smalltalk and CLOS.
3. How robust is the iterator? It can be dangerous to modify an aggregate while you're
traversing it. If elements are added or deleted from the aggregate, you might end up
accessing an element twice or missing it completely. A simple solution is to copy the
aggregate and traverse the copy, but that's too expensive to do in general.
4. Additional Iterator operations. The minimal interface to Iterator consists of the operations
First, Next, IsDone, and Currentltem.4 Some additional operations might prove useful. For
example, ordered aggregates can have a Previous operation that positions the iterator to the
previous element.
5. Using polymorphic iterators in C++.Polymorphic iteratorshave their cost. They require the
iterator object to be allocated dynamically by a factory method. Hence they should be used
only when there's a need for polymorphism. Otherwise use concrete iterators, which can be
allocated on the stack.
6. Iterators may have privileged access. An iterator can be viewed as an extension of the
aggregate that created it.The iteratorand the aggregate are tightly coupled. We can express
this close relationship in C++ by making the iterator a friend ofits aggregate.
7. Iterators for composites. External iterators can be difficult to implement over recursive
aggregate structures like those in the Composite (163) pattern, because a position in the
structure may span many levels of nested aggregates. Therefore an external iterator has to
store a path through the Composite to keep track of the current object
8. Null iterators. A Nulllterator is a degenerate iterator that's helpful for handling boundary
conditions. By definition, a Nulllterator is always done with traversal; that is, itsIsDone
operation always evaluates to true.
5.Discuss the implementation steps of the Mediator design pattern.
ans:
• a behavior that's distributed between several classes should be customizable without a lot
of subclassing.
Participants:
• Mediator (DialogDirector)
• ConcreteMediator (FontDialogDirector)
- each colleague communicates with its mediator whenever it would have otherwise
communicated with another colleague.
ans:
Intent: Without violating encapsulation, capture and externalize an object's internal state so
that the object can be restored to this state later.
Motivation:
In that case, simply moving the rectangle back to its original location won't necessarily
achieve the desired effect.
• a snapshot of (some portion of) an object's state must be saved so that it can be restored to
that state later, and
• a direct interface to obtaining the state would expose implementation details and break the
object's encapsulation.
Participants:
• Memento (SolverState) - stores internal state of the Originator object. The memento may
store as much or as little of the originator's internal state as necessary at its originator's
discretion. - protects against access by objects other than the originator. Mementos have
effectively two interfaces.
ans:
Intent: Define a one-to-many dependency between objects so that when one object changes
state, all its dependents are notified and updated automatically.
Motivation:
• When a change to one object requires changing others, and you don't know how many
objects need to be changed.
• When an object should be able to notify other objects without making assumptions about
who these objects are.In other words, you don't want these objects tightly coupled.
Participants:
• Subject
- knows its observers. Any number of Observer objects may observe a subject.
• Observer
- defines an updating interface for objects that should be notified ofchanges in a subject.
• ConcreteSubject
• ConcreteObserver
ans:
The model view controller is a relatively old pattern that was originally introduced in the
Smalltalk programming language. As one might suspect, the pattern divides the
application into three subsystems: model, view, and controller.
The pattern separates the application object or the data, which is termed the Model,
from the manner in which it is rendered to the end-user (View) and from the way in which
the end-user manipulates it (Controller).
In contrast to a system where all of these three functionalities are lumped together
(resulting in a low degree of cohesion), the MVC pattern helps produce highly cohesive
modules with a low degree of coupling. This facilitates greater flexibility and reuse. MVC
also provides a powerful way to organise systems that support multiple presentations of
the same information.
The model, which is a relatively passive object, stores the data. Any object can play the
role of model. The view renders the model into a specified format, typically something
that is suitable for interaction with the end user.
For example, if the model stores information about bank accounts, a certain view may
display only the number of accounts and the total of the account balances. The
controller captures user input and when necessary, issues method calls on the model to
modify the stored data. When the model changes, the view responds by appropriately
modifying the display
In a typical application, the model changes only when user input causes the controller to
inform the model of the changes. The view must be notified when the model changes.
Both the controller and the view communicate with the user through the UI.
This means that some components of the UI are used by the controller to receive input;
others are used by the view to appropriately display the model and some can serve both
purposes (e.g., a panel can display a figure and also accept points as input through
mouseclicks)
It could also be the case that the model is changed not via one of the controllers, but
through some other mechanism. In this case, the model must notify all associated views
of the changes.
Benefits:
1. Cohesive modules: Instead of putting unrelated code (display and data) in the same
module, we separate the functionality so that each module is cohesive.
2. Flexibility: The model is unaware of the exact nature of the view or controller it is working
with. It is simply an observable. This adds flexibility.
3. Low coupling: Modularity of the design improves the chances that components can be
swapped in and out as the user or programmer desires. This also promotes parallel
development, easier debugging, and maintenance.
4. Adaptable modules: Components can be changed with less interference to the rest of the
system.
5. Distributed systems: Since the modules are separated, it is possible that the three
subsystems are geographically separated.
2.Write and explain the code for implementation of model and view.
ans:
The class maintains itemList and selectedList, which respectively store the items created but
not selected, and the items selected. The constructor initialises these containers.
The setUIContext method in the model in turn invokes the setUIContext on Item.
The addItem method is simple: it just stores the item in itemList and redraws the screen.
When an item is selected by the user, the model marks it as selected by transferring the item
from itemList to selectedList as below.
The class maintains itemList and selectedList, which respectively store the items created but
not selected, and the items selected. The constructor initialises these containers.
The setUIContext method in the model in turn invokes the setUIContext on Item
When an item is selected by the user, the model marks it as selected by transferring the item
from itemList to selectedList as below.
Selected items are deleted using the deleteSelectedItems.
The getItems method is used by the controller to determine which item is selected. The view
uses the same method to render the items.
ans:
In the context of implementing the undo operation, a few issues need to be highlighted.
• Single-level undo versus multiple-level undo A simple form of undo is when only one
operation (i.e., the most recent one) can be undone. This is relatively easy, since we can afford
to simply clone the model before each operation and restore the clone to undo.
• Undo and redo are unlike the other operations If an undo operation is treated the same as
any other operation, then two successive undo operations cancel each other out, since the
second undo reverses the effect of the first undo and is thus a redo. The undo (and redo)
operations must therefore have a special status as meta-operations if several operations
must be undone.
• Not all things are undoable This can happen for two reasons. Some operations like ‘print file’
are irreversible, and hence undoable. Other operations like ‘save to disk’ may not be worth
the trouble to undo, due to the overheads involved.
• Blocking further undo/redo operations It is easy to see that uncontrolled undo and redo
can result in meaningless requests. In general, it is safer to block redo whenever a new
command is executed.
Consider a situation where we have the sequence: Select(a), undo, Select(a), redo.
The redo tries to mark a as selected, and this could result in an exception depending on how
things are implemented.
A more severe problem arises with Create Rectangle(r), Colour Rectangle(r, blue), undo,
Delete(r), redo. Here, the redo will attempt to colour a rectangle that does not exist any more.
4.Sequence diagram for adding a line
Adding a line Since every command is represented by a Command object, the first order
of task when the Draw Line command is issued is to instantiate aLineCommand object.
We assume that we do this after the user clicks the first endpoint although there is no
reason why it could not have been created immediately after receiving the command.
In its constructor, LineCommand creates a Line object with one of its endpoints specified.
The two methods beginCommand and endCommand are for these two purposes. In the
course of execution of the beginCommand method, the undo manager ensures the the
Line object gets added to the model.
This way, should the view be refreshed, the partial line will be shown on the screen. When
the command is completed and the endCommand method is executed, the undo
manager pushes the command onto the history stack.
This way the latest command is always at the top of this stack.
ans:
Rendering the items A tricky issue regarding the design is how the items should be rendered.
Rendering is the process by which the data stored in the model is displayed by the view.
• The technology and tools that are used in creating the UI For instance, we are using the
Java’s Swing package, which means that our drawing panel is a JPanel and the drawing
methods will have to be invoked on the associated Graphics object.
• The item that is stored If a line is stored by its equation, the code for drawing it would be
very different from the line that is stored as two end points.
The technology and tools are known to the author of the view, whereas the structure of the
item is known to the author of the items. Since the needed information is in two different
classes, we need to decide which class will have the responsibility for implementing the
rendering. We have the following options:
Option 1:
Let us say that the view is responsible for rendering, i.e., there is code in the view that
accesses the fields of each item and then draws them.
Since the model is storing these items in a polymorphic container, the view would have to
query the type of each item returned by the enumeration in order to choose the
appropriate method(s).
Option 2:
If the item were responsible, each item would have a render method that accesses the
fields and draws the item.
The problem with this is that the way an object is to be rendered often depends on the
tools that we have at our disposal. For instance, consider the problem of rendering a
circle: a circle is almost always drawn as a sequence of short line segments.
If the only method given in the toolkit is that for drawing lines, the circle will have to be
decomposed into straight lines.
In addition to the set of tools, there are other specific features that the technology has.
Using the Swing package in Java, for instance, implies that all the drawing is done by
invoking the methods on the Graphics object associated with the drawing panel.
ans:
The software allows us to delete lines, circles, or labels by selecting the item and then
invoking the delete operation.
When an item is selected, it is displayed in red, as opposed to black. The selection is done
by clicking with the arrow (default) cursor.
Lines are selected by clicking on one end point, circles are selected by clicking on the
center, and labels are selected by clicking on the label.
1. The user gives the command through a button click. This is followed by a mouse click to
specify the item. Both of these are detected in the view and communicated to the controller.
2. In order to decide what action the controller must take, we need to figure out how the
system will keep track of the selected items. Since the view is responsible for how these will
be displayed (in red, for instance) the view must be able to recognise these as selected when
updating the display.
3. The next step is to iterate through the (unselected) items in the model to find the item (if
any) that contains the point. Since the model is to be used strictly as a repository for the
data, the task of iterating through the items is done in the controller, which then invokes the
methods of the model to mark the item as selected.
4. Model notifies view, which renders the unselected items in the default colour (black) and
the selected items in red. View gets an enumeration of the two lists separately and uses the
appropriate colour for each. Note that model only stores a separate list of the selected items.
It is the view that decides how the two lists are to be rendered.
9.
Module 5
1. Explain the architecture of the client/server system.
ans:
we assume that although the client/server systems we build may have multiple clients,
they will have just one server.
It is not difficult to extend the techniques to multiple servers, so this is not a serious
restriction. Figure shows a system with one server and three clients.
Each client runs a program that provides a user interface, which may or not be a GUI. The
server hosts an object-oriented system.
Like any other client/server system, clients send requests to the server, these requests
are processed by the object-oriented system at the server, and the results are returned.
The results are then shown to end-users via the user interface at the clients.
1. By using object-oriented support software: The software solves the problem by the use of
proxies that receive method calls on ‘remote’ objects, ship these calls, and then collect and
return the results to the object that invoked the call. The client could have a custom-built
piece of software that interacts with the server software.
2. By avoiding direct use of remote objects by using the Hyper Text Transfer Protocol (HTTP).
The system sends requests and collects responses via encoded text messages. The object(s)
to be used to accomplish the task, the parameters, etc., are all transmitted via these
messages.
ans:
The world-wide web is the most popular medium for hosting distributed applications.
Increasingly, people are using the web to book airline tickets, purchase a host of
consumer goods, make hotel reservations, and so on.
The browser acts as a general purpose client that can interact with any application that
talks to it using the Hyper Text Transfer Protocol (HTTP). One major characteristic of a
web-based application system is that the client (the browser), being a general-purpose
program, typically does no application-related computation at all. All business logic and
data processing take place at the server.
Typically, the browser receives web pages from the server in HTML and displays the
contents according to the format, a number of tags and values for the tags, specified in it.
In this sense, the browser simply acts as a ‗dumb‘ program displaying whatever it gets
from the application and transmitting user data from the client site to the server The
HTML program shipped from a server to a client often needs to be customised: the code
has to suit the context.
For example, when we make a reservation on a flight, we expect the system to display the
details of the flight on which we made the reservation. This requires that HTML code for
the screen be dynamically constructed.
This is done by code at the server. For server-side processing, there are competing
technologies such as Java Server Pages and Java Servlets, Active Server Pages (ASP), and
PHP. In this book we study java servlets.
ans:
Developing User Requirements: As in any system, the first task is to determine the system
requirements. We will, as has been the case throughout the book, restrict the functionality so
that the system‘s size is manageable.
1. The user must be able to type in a URL in the browser and connect to the library system.
2. Users are classified into two categories: superusers and ordinary members.
3. Some commands can be issued from the library only. These include all of the commands
that only the superuser has access to and the command to issue books.
4. A superuser cannot issue any commands from outside of the library. They can log in, but
the only command choice will be to exit the system.
5. Superusers have special user ids and corresponding password. For regular members, their
library member id will be their user id and their phone number will be the password.
Interface requirements:It turns out that due to the nature of the graphical user interface, an
arbitrarily large number of sequences of interactions are possible between the user and the
interface.
we show the process of logging in to the system. When the user types in the URL to access
the library system,
1. The Issue Book command is available only if the user logs in from a terminal in the library.
2. Commands to place a hold, remove a hold, print transactions, and renew books are
available to members of the library (not superusers) from anywhere.
3. Certain commands are available only to superusers who log in from a library terminal:
these are for returning or deleting books, adding members and books, processing holds, and
saving data to and retrieving data from disk.
Add Book:The system must then call the appropriate method in the Library class to create a
Book object and enter it into the catalog. The result of the operation is displayed in the
Command Completed state.
Add Member, Return Book, Remove Book:The requirements are similar to the ones for adding
books. We need to accept some input (member details or book id) from the user, access the
Library object to invoke one of its methods, and display the result.
Place Hold, Remove Hold, Print Transactions: The requirements for these are similar to those
for issuing a book, so we omit their description.
Renew Books: The system must list the title and due date of all the books loaned to the
member. For each book, the system must also present a choice to the user to renew the book.
ans:
HTML code displays text, graphics such as images, links that users can click to move to other
web pages, and forms for the user to enter data. We will now describe the essential code for
doing these.
An HTML program can be thought of as containing a header, a body, and a trailer. The header
contains code like the following:
The first four lines are usually written as given for any HTML file. We do not elaborate on
these, but observe words such as html and head that are enclosed between angled
brackets (< and >). They are called tags.
The text between the start and end tags is the element content.
In the fifth line we see the tag title, which defines the string that is displayed in the title
bar. The idea is that the string A Web Page will be displayed in the title bar of the browser
when this page is displayed.
As a sample body, let us consider the following.
The body contains code that determines what gets displayed in the browser’s window.
Some tags may have attributes, which provide additional information. For example, see
the line
where the tag span has its attribute style modified, so that the text will be in blue colour:
the reader may have guessed that rgb stands for the amount of red, green,and blue in the
color, whose the values can range from 0 to 255.
They are always specified in the start tag of an HTML element. The body contains code to
display the string An Application in the font Lucida bright, bolded, italicised, and in blue
color. The last line of the file is </html>.
POST Method
ans:
Marshalling (Serialization)
Definition: The process of converting an object, data structure, or message into a format
suitable for storage or transmission. This process prepares the data to be sent over a
network or saved to a file.
Purpose: Ensures that the data is in a standardized format that the receiver can interpret.
Example in SAP or Integration:
In an SAP system, marshalling might involve converting an ABAP structure or internal
table into an XML, JSON, or binary format to be sent as a web service payload.
Example:
Demarshalling (Deserialization)
Definition: The reverse process of marshalling, where the formatted data (e.g., JSON,
XML, binary) is converted back into an object, data structure, or message that the
application can process.
Purpose: Converts transmitted or stored data into a usable in-memory representation.
Example in SAP or Integration:
Converting an incoming JSON payload into an ABAP structure to be processed
further.
Example:
7.Explain the steps used to set up a remote object system.
ans:
steps:
The first step in implementing a remote object system is to define the system
functionality that will be exported to clients, which implies the creation of a Java
interface.
In the case of RMI, the functionality exported of a remote object is defined via what is
called a remote interface.
A remote interface is a Java interface that extends the interface java.rmi.Remote, which
contains no methods and hence simply serves as a marker.
clints are registered to accessing methods defined in the remote interface. We call such
method calls remote method invocations.
remote interfaces are defined, the next step is to implement them via remote classes.
Parameters to and return values from a remote method may be of primitive type, of remote
type, or of a local type.
Since it is a remote class, Book must be compiled using the RMI compiler by invoking the
command rmic as below.
rmic book
The scheme has the consequence that any changes made to the state of the object by remote
method invocations are reflected in the original remote object. If the second client now
invokes the method getA, the updated value 5 is returned to it.
3. Create a server:
Before a remote object can be accessed, it must be instantiated and stored in an object
registry, so that clients can obtain its reference. Such a registry is provided in the form of the
class java.rmi.Naming.
The complete code for activating and storing the Book object is shown below.
4. Set up the client.
A client may get a reference to the remote object it wants to access in one of two ways:
1. It can obtain a reference from the Naming class using the method lookup.
Then compile the three Java files in server and then invoke the command
rmic Book
Run RMI registry and the server program using the following commands (on Windows).