This document outlines the course CSE 6007 - Design and Development Open Multi-tier Application at United International University for the Fall 2012 trimester. It includes information on the course assessment breakdown, reference books, 13 weekly lectures covering various design patterns and multi-tier application topics, and the final exam date at the end of the semester.
1. United International University (UIU)
Dept. of Computer Science & Engineering (CSE)
Trimester: Fall 2012
Course Outlines
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof.. S M Monzurur Rahman (mrahman99@yahoo.com)
Assessment:
Component Marks(%)
Attendance 5
Continuous Assessment - Class Test 10
Continuous Assessment - Project 15
Midterm 30
Final 40
Total 100
Reference Book
1. Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
2. Patterns of Enterprise Application Architecture, By Martin Fowler
3. WCF 4.0 Multi-tier Services Development with LINQ to Entities By Mike Liu
Lecture 1
• Introduction to Design Pattern
• The strategy Design Pattern
Lecture 2
• Value Object pattern.
• The Decorator Design Pattern
• The Factory Design Pattern
Lecture 3
• The Observer Design Pattern
• The Singleton Design Pattern
• The Adapter Design Pattern
Lecture 4
• **** Class Test
• Registry design pattern
1
2. • Dependency Injection Pattern
Lecture 5
• The Facade Design Pattern
• The Template Design Pattern
• Model-View-Controller
Lecture 6
• Mid-Exam
Lecture 7
• Enterprise Pattern
• SOAP
• Open and Close Multi-tier
Lecture 8
• The Composite Design Pattern
• The Visitor Design Pattern
• The Proxy Design Pattern
Lecture 9
• SOA Design pattern
• SOA in .NET
• Web services
• SOAP
• WCF: Windows Communication Foundation
Lecture 10
• **** Class Test
• Implementing a Basic WCF Service
• Creating a client to consume the WCF service
Lecture 11
• MVC3-Rajor
Lecture 12
• Project Demonstration
• Review
Lecture 13
• Final Exam
END OF SEMESTER!!! ENJOY!!!
2
3. United International University
Trimester: Fall 20012
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof. Dr. Monzurur Rahman (mrahman99@yahoo.com)
Week 1: Introduction and The strategy Design Pattern
Design Pattern
A design pattern is:
• a standard solution to a common programming problem. Some problems come up
over and over in object-oriented programming. A design pattern represents a
codified solution to a problem, an idiom that you can apply when you encounter it
again.
• a shorthand for communicating design concepts. Design patterns provide a
vocabulary for sharing software designs with other programmers, both verbally
and in documentation and specifications. Rather than a wordy description like
“this class steps through a collection and returns one element at a time”, you can
just say “this class is an iterator.”
• a particular shape of object diagram, object model, or module dependency
diagram. Many patterns reveal themselves this way, often by reducing the degree
of coupling between components to make the design more amenable to change.
• The bible for design patterns is the so-called “Gang of Four” book, Design
Patterns: Elements of Reusable Object-Oriented Software, by Gamma, Helm,
Johnson, and Vlissides, which is a recommended course text.
UIU Week 1, CSE 6087 1/23
4. Example# 1
• Lets we have an old object and interface which takes old object
• After some time, interface has been changed and issue is how to handle the
change.
• Design pattern gives the solution to this problem using adaptor pattern.
UIU Week 1, CSE 6087 2/23
5. Example# 2
• Lets you are designing a web site which has the following pages.
• There are a lot of interactions between pages and which makes the programming
complex. In that case a mediator design pattern provides a good solution.
UIU Week 1, CSE 6087 3/23
6. Kinds of Design Patterns
1. Architectural Patterns
An architectural pattern expresses a fundamental structural organization or
schema for software systems. It provides a set of predefined subsystems, specifies
their responsibilities, and includes rules and guidelines for organizing the
relationships between them.
Example:
Distributed
Event-driven
Frame-based
Layered
MVC
Tier – Open / Close
2. Creational Patterns
• Creational design patterns are design patterns that deal with object creation
mechanisms, trying to create objects in a manner suitable to the situation.
• .Example:
Factory
Prototype
Singleton pattern
Builder pattern
3. Structural patterns
• Structural design patterns are design patterns that ease the design by identifying a
simple way to realize relationships between entities.
• Example:
Adapter
UIU Week 1, CSE 6087 4/23
7. Bridge
Proxy
Aggregate pattern
4. Behavioral patterns
• Behavioral design patterns are design patterns that identify common communication
patterns between objects and realize these patterns. By doing so, these patterns
increase flexibility in carrying out this communication.
• .Example:
Chain of responsibility
Mediator
Visitor
Riehle and Zullighoven make similar distinctions, but seem to partition the different
kinds of patterns among analysis, design, and implementation. They define the terms
conceptual patterns, design patterns, and programming patterns as follows:
1. Conceptual Patterns
A conceptual pattern is a pattern whose form is described by means of terms and
concepts from an application domain.
2. Design Patterns
A design pattern is a pattern whose form is described by means of software
design constructs, for example objects, classes, inheritance, aggregation and use-
relationship.
3. Programming Patterns
A programming pattern is a pattern whose form is described by means of
programming language constructs
Qualities of a Pattern
A well written pattern should exhibit several desirable qualities and they are:
UIU Week 1, CSE 6087 5/23
8. • Encapsulation and Abstraction
Each pattern encapsulates a well-defined problem and its solution in a particular
domain.
• Openness and Variability
Each pattern should be open for extension or parametrization by other patterns so
that they may work together to solve a larger problem.
• Generativity and Composability
Each pattern, once applied, generates a resulting context which matches the initial
context of one or more other patterns in a pattern language. These subsequent
patterns may then be applied to progress further toward the final goal of
generating a "whole" or complete overall solution.
• Equilibrium
Each pattern must realize some kind of balance among its forces and constraints.
This may be due to one or more invariants or heuristics that are used to minimize
conflict within the solution space. The invariants often typify an underlying
problem solving principle or philosophy for the particular domain, and provide a
rationale for each step/rule in the pattern.
Patterns and Algorithms
• Algorithms and data structures may be employed in the implementation of one or
more patterns, but algorithms and data structures generally solve more fine-
grained computational problems like sorting and searching.
• Patterns are typically concerned with broader architectural issues that have larger-
scale effects. The design patterns in [GoF] address people and development issues
like maintainability, reusability, communicating commonality and encapsulation
variation. These are issues that matter to the people who need to create and
evolve/grow these software systems over time.
UIU Week 1, CSE 6087 6/23
9. • Algorithms and data structures are usually concerned almost exclusively with
optimizing space or time or some other aspect of computational complexity and
resource consumption.
Patterns and Frameworks
One thing closely related to design patterns and object-orientation is a software
framework.
• A framework supplies the infrastructure and mechanisms that execute a policy for
interaction between abstract components with open implementations.
• A software framework is a reusable mini-architecture that provides the generic
structure and behavior for a family of software abstractions, along with a context
of memes/metaphors which specifies their collaboration and use within a given
domain.
• A framework is a set of cooperating classes that make up a reusable design for a
specific class of software. A framework provides architectural guidance by
partitioning the design into abstract classes and defining their responsibilities and
collaborations. A developer customizes a framework to a particular application by
subclassing and composing instances of framework classes.
Example – MVC framework
There are three major components of MVC:
• Model: Encapsulates core data and logic. Model is often related with the business
logic of the application. It knows all the data that needs to be displayed. It is
always isolated from the User Interface (UI) and the way data needs to be
displayed.
• View: It is the UI part of the application. It uses read-only methods of the model
and queries data to display them to the end users. It may be a window GUI or a
UIU Week 1, CSE 6087 7/23
10. HTML page. View encapsulates the presentation of the data, there can be many
views of the common data
• Controller: It acts as a interacting glue between models and views. It accepts
input from the user and makes request from the model for the data to produce a
new view.
UIU Week 1, CSE 6087 8/23
11. The [GoF] book describes the major differences between design patterns and frameworks
as follows:
• 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,
design patterns have to be implemented each time they are used. Design patterns
also explain the intent, trade-offs, and consequences of a design.
• Design patterns are smaller architectural elements than frameworks. A typical
framework contains several design patterns but the reverse is never true.
• Design patterns are less specialized than frameworks. Frameworks always have a
particular application domain. In constrast, design patterns can be used in nearly
any kind of application. While more specialized design patterns are certainly
possible, even these wouldn't dictate an application architecture.
UIU Week 1, CSE 6087 9/23
12. Design Principles
• Encapsulate aspects of your application that vary
• Program to interfaces, not implementations
• Favor composition over inheritance
• Classes should be open for extension but closed for modification
• Strive for loosely coupled designs between objects that interact
• Depend upon abstraction, not concrete classes
Pattern Catalogs
A pattern catalog is a collection of related patterns (perhaps only loosely or informally
related). It typically subdivides the patterns into at least a small number of broad
categories and may include some amount of cross referencing between patterns.
Design Anti-Patterns
• A design anti-pattern is an example of design that initially appeared to be a good
idea, but later turned out to be a bad one.
• Anti-patterns are examples of bad design and bad coding practice. Examples of
object-oriented anti-patterns:
a) Creating massive classes with a huge number of methods.
b) Too many utility classes that perform too many operations. A utility class is
one that has only static methods, no state and which performs operations on
objects that are passed in.
• Significance of Design Anti-Patterns
Anti-patterns are useful for the same reason that patterns are useful, anti-patterns provide
a way to document and spot bad design and to (hopefully) provide remedies. It's a good
idea to know about anti-patterns so that your code doesn't use any, so that they can be
recognised the next time code is maintained and so that their impact can be appreciated at
the next code review. They should be identified as early as possible in the software life-
cycle as it's easier to re-design code than unpick its implementation.
UIU Week 1, CSE 6087 10/23
13. Criticisms of Patterns
• Some have criticized design patterns, pointing out that they don't provide reuse
nor do they differ significantly from other abstractions. The purpose of design
patterns is to capture commonality at the design level. Patterns can be reused once
implemented; however, as soon as the design is implemented, it has become
specific to the particular language and environment in which it will be deployed.
The implementation of a persistence layer pattern would be radically different on
a handheld device compared to one for a server environment. The pattern for
these two environments will have some elements in common and this
commonality can be reused at the design level. The pattern can then be
decomposed and refined, one for each environment, and the individual patterns
can be reused and implemented. The two patterns and the common part can then
be made publically available from the Portland Pattern Repository. Patterns and
their implementations compliment each other, however, one isn't a replacement
for the other and patterns are design-level entities.
• I've often thought design patterns were clever, but a toy when compared to reality.
I think in real systems we use thousands of different patterns and morph them and
hybridize them as we go. Building real software out of a few toy patterns is like
building a Lamborghini out of lego. I think what we really need then are ways to
dynamically discover the patterns we care about at a given moment, I think of it
as "data mining the code".
1. Strategy Pattern
• Behavioral Pattern
• Encapsulates an algorithm inside a class.
• Defines a family of interchangeable encapsulated algorithms that receives the
same input type and provides the same output type in different manners that can
be determined in run-time.
UIU Week 1, CSE 6087 11/23
14. Why do we need?
Consider the following basic design:
• Carry() is defined in base class and run() is overridden in the derived classes
as required.
• Suddenly you recognise that, as this is for worldwide cars, there are some
cars, which go for race.
• Only change required is to add a race() method in the base class so some
cars can go for the race.
• User starts the Demo with the above change , Some thing went horribly wrong:
"Taxi's started racing"
"RaceCar's started carrying passengers"
• Now code needs to be modified.
Modify Taxi Class - Race() to do nothing
Modify RaceCar Class -Carry() to do nothing
• But consider about ToyCar they do not race nor they do not Carry.
Create the ToyCar Class
- Race() to do nothing
UIU Week 1, CSE 6087 12/23
15. -Carry() to do nothing
• As long as new type of car's come, the more modification is required in base
class and derived classes (need to override code). This is the problem to
maintain the code. To solve this problem Strategy Design Patterns comes as a
solution.
Solution
• In order to solve the above problem we separate car class than car behavior i.e.
Separate the algorithm code from the class code.
• We use "Program to an interface, not an implementation” The interfaces can
be designed as follows:
UIU Week 1, CSE 6087 13/23
16. • "Favor Composition over inheritance" The refined design is as follows:
• In Strategy design pattern : "Define a family of algorithms(strategies),
encapsulate each one, and make them interchangeable. Strategy lets the
algorithm vary independently from clients that use it.". Now look at the code
level solution:
Public abstract class Car
{
UIU Week 1, CSE 6087 14/23
17. CarryBehaviour carryBehaviour;
RaceBehaviour raceBehaviour;
public Car()
{
}
public abstract void run();
public void race()
{
raceBehaviour.race();
}
public void carry()
{
carryBehaviour.carry();
}
public void setraceBehaviour(RaceBehaviour rb)
{
raceBehaviour = rb;
}
public void setcarryBehaviour(CarryBehaviour cb)
{
carryBehaviour = cb;
}
}
UIU Week 1, CSE 6087 15/23
18. RaceBehaviour (Interface), RaceCar (Class) & RaceNoWay (Class):
public interface RaceBehaviour
{
public void race();
}
public class RaceCar implements RaceBehaviour
{
public void race()
{
system.out.println("I am racing");
}
}
public class RaceNoWay implements RaceBehaviour
{
public void race()
{
system.out.println("I can't race");
}
}
CarBehaviour (Interface), CarryPeople (Class) , NonCarrier (Class) &
CarryLoad (Class):
public interface CarryBehaviour
{
public void carry();
}
public class CarryPeople implements CarryBehaviour
{
public void carry()
{
system.out.println("I can carry only people");
}
}
public class NonCarrier implements CarryBehaviour
{
public void carry()
{
system.out.println("I can't carry");
}
}
UIU Week 1, CSE 6087 16/23
19. public class CarryLoad implements CarryBehaviour
{
public void carry()
{
system.out.println("I can carry only Load");
}
}
Car Class
Public class Taxi extends Car
{
public Taxi()
{
carryBehaviour = new CarryPeople();
raceBehaviour = new RaceNoWay();
}
public void run()
{
System.out.println("Running a Taxi");
}
}
Jeep Class
Public class Jeep extends Car
{
public Jeep ()
{
carryBehaviour = new CarryLoad();
raceBehaviour = new RaceNoWay();
}
public void run()
{
System.out.println("Running a Jeep");
}
}
UIU Week 1, CSE 6087 17/23
20. RaceCar Class
Public class RaceCar extends Car
{
public RaceCar ()
{
carryBehaviour = new NonCarrier();
raceBehaviour = new RaceCar();
}
public void run()
{
System.out.println("Going for Race");
}
}
ToyCar Class
Public class ToyCar extends Car
{
public ToyCar ()
{
carryBehaviour = new NonCarrier();
raceBehaviour = new RaceNoWay();
}
public void run()
{
System.out.println("Play with ToyCar ");
}
}
RentalCar Class
Public class RentalCar extends Car
{
public RentalCar ()
{
carryBehaviour = new CarryPeople();
raceBehaviour = new RaceNoWay();
}
public void run()
{
System.out.println("I am Rented Car");
}
}
UIU Week 1, CSE 6087 18/23
21. Small Demo
Public class WorldCarSimulator
{
public static void main(string[] args)
{
Car Ferrari = new RaceCar();
Ferrari.carry();
Ferrari.race();
Ferrari.run();
Car RoadRunnerTaxi = new Taxi();
RoadRunnerTaxi.carry();
RoadRunnerTaxi.race();
//Changing the behaviour dynamically
RoadRunnerTaxi.setraceBehaviour(new RaceBehaviour());
RoadRunnerTaxi.race();
}
}
• When new thing comes we change outside of the class i.e. when new algorithm
comes (behavior), we need to implement that new behavior in a new interface not
in class level and that behavior can set dynamically using set method.
• Any class change their behavior outside of the class e.g.
//Changing the behaviour dynamically
RoadRunnerTaxi.setraceBehaviour(new RaceBehaviour());
RoadRunnerTaxi.race();
UIU Week 1, CSE 6087 19/23
22. Lab Work (C# or Java):
The problem ('design smell') associated with this approach is simply the way we
are placing the implementation of the actions Eat() and MakeNoise() inside the concrete
classes. This doesn't exactly lead to a maintainable design. For example, suppose we
want to extend our animal kingdom by introducing an AllyCat class. An AllyCat might
have different implementations of Eat() (eating out of the trash), but still have the same
kind of MakeNoise() (moew) implementation. You might think, "well, we can just derive
from the concrete class Cat, and override the Eat() method with our own AllyCat.Eat()
implementation" and you're right, you can. However, extending behavior through
hierarchal inheritance should be avoided. Not only that, designs like this can lead to
duplicate code.
Instead, you should compose classes with isolated algorithm implementations.
The goal is to separate varying-code from non-varying code. A quick way to identify
non-varying code aspects of your classes is through "has-a" relationships. A Dog "has-a"
distinct eating behavior, a Cat "has-a" distinct eating behavior, an AllyCat "has-a"
distinct eating behavior, so on and so forth... From our classes and implementation, we
have noise behaviors and eating behaviors.
Provide a better solution for the above problem. You must provide the followings
in your answer.
a.) UML for your solution.
b.) Java/C# codes for the solution.
The Solution
The solution to basic problems is to implement a Strategy pattern. Consider the following
architecture:
UIU Week 1, CSE 6087 20/23
23. And taking a peek in some of the Cat, Ally Cat and Dog code:
UIU Week 1, CSE 6087 21/23
25. All that we have done with this new architecture is delegate the "making noise" and
"eating" to behavioral classes that specifically handle the task. We have delegated control
to the behavioral classes. This is a much better extensible and coherent design and often
leads itself to better to code reuse.
Whenever we create classes that are composed of behavioral actions, we call these
compositions. Classes such as Dog, Cat, and AllyCat are compositions of behaviors and
gain their behavior through composition, not inheritance. Inheritance (like the previous
architecture) can lead to unintended consequences when fiddling with the superclass and
is more prone to breaking existing code.
*************** End of Week 1 **************
UIU Week 1, CSE 6087 23/23
26. United International University
Trimester: Fall 2012
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof. Dr. Monzurur Rahman (mrahman99@yahoo.com)
Week 1: Decorator and Factory Design Pattern
2. Decorator Design Pattern
• Structural Pattern
• Also known as wrapper.
• The Decorator Pattern is used for adding additional functionality to a particular
object as opposed to a class of objects. It is easy to add functionality to an entire
class of objects by subclassing an object, but it is impossible to extend a single
object this way. With the Decorator Pattern, you can add functionality to a single
object and leave others like it unmodified.
Example
• Consider you have a following computer class with a description method:
UIU Week 1, CSE 6087 1/19
27. • After some time you need to add to the description method a disk:
UIU Week 1, CSE 6087 2/19
28. • You need again to modify the computer class again as follow:
• In this way if you need again and again modification to your class then it is
difficult to manage since you need to touch the actual class again and again.
• To solve the above problem, Decorator pattern comes as a rescue. The design
pattern suggests you to create a wrapper class and place the instance of the class
to the wrapper class and wrapper class allow you to add new functionality i.e.
changing the description method. In this way you do not need to modify the
computer class.
UIU Week 1, CSE 6087 3/19
29. Solution
In order to solve the above problem you can design the classes as follows:
• Here Monitor description method calls Disk description method and Disk
description method in turn call Computer method.
• How to code the above Decorator design pattern.
o Computer class which has a minimal description
UIU Week 1, CSE 6087 4/19
30. o We need a basis of Decorator class which is the abstract class as well as
the derived class from the main Computer class.
o When Disk come to the table then we can design Disk decorator as
follows:
UIU Week 1, CSE 6087 5/19
31. o Similarly if you need another Decorator e.g. CD then you can design that
as follows:
o Similarly if you need another Decorator e.g. Monitor then you can design
that as follows. Do not forget that in the constructor you can pass CD
object for Computer c parameter since CD is itself a Computer type.
UIU Week 1, CSE 6087 6/19
32. o The following way you can use the decorator patterns in the claient
program.
o The output will be – You are getting a computer and a disk and a monitor
and a CD and a CD
• The idea behind a decorator pattern is that you can customize your objects by
adding multiple wrappers over and over again even the same wrapper twice or
more times.
• So using Decorator pattern you can customize your object each time using a
wrapper without modifying your codes.
UIU Week 1, CSE 6087 7/19
33. Decorator Applicability
• When you need to add responsibilities to individual objects
– dynamically and transparently, that is, without affecting other objects
– responsibilities that can be withdrawn
• when extension by subclassing is not practical
– large number of independent extensions are possible and would
produce an explosion of subclasses to support every combination
– a class definition may be hidden or otherwise unavailable for
subclassing
Decorator Advantages
• Provide an alternative to subclassing.
• Responsibilities can be added / removed at run-time by attaching and detaching
them
• Providing different Decorator classes for a specific Component class lets you mix
and match responsibilities
• Easy to add a property twice
• Pay-as-you-go approach
o don't bloat, but extend using fine-grained Decorator classes
• Functionality can be composed from simple pieces
o thus, an application does not need to pay for features it doesn't use
• A fine-grained Decorator hierarchy is easy to extend
Decorator Disadvantages
• Lots of Little Objects
UIU Week 1, CSE 6087 8/19
34. o a design that uses Decorator often results in systems
o composed of lots of little objects that all look alike
o objects differ only in the way they are interconnected, not in their class or
in the value of their variables
o these systems are easy to customise by those who understand them, they
can be hard to learn and debug
Factory Design Pattern
• Creational Pattern - Provide an interface for creating families of related or
dependent objects without specifying their concrete classes.
• In OOP, the most common way to create an object is with the new operator, the
language construct provided to do just that. But in some cases, new can be
problematic. For instance, the creation of many kind of objects requires a series of
steps: i) you may need to compute or fetch the object’s initial settings; ii) you
might have to choose which of many sub classes to instantiate; iii) or perhaps you
have to create a batch of other helper objects before you can create the object you
need. In those cases, new is a “process” more than an operation—a cog
(component) in a bigger machine.
• In Factory Pattern we have the Problem : How can you create such “complex”
objects easily and conveniently—without cut-and-paste programming?
• The Solution to the above answer- Create a “factory”—a function or a class
method— to “manufacture” new objects.
Example
• Consider a situation where we need a database connection depending on the
user’s choice:
UIU Week 1, CSE 6087 9/19
35. • In one way you can solve the above problem using the following function:
• In the above, OracleConnection, SqlServerConnection etc. need to be same class
as Connection which Factory Design Pattern Provides.
Solution from Factory Pattern
• You need a factory pattern to make the better solution for the above problem.
• In the Factory Pattern, a factory method defines what functions must be available
in the non-abstract or concrete factory. These functions must be able to create
objects that are extensions of a specific class. Which exact subclass is created will
depend on the value of a parameter passed to the function.
• The first version of the Factory class is as follows, The CreateConnection() is
called creational method. We need to make the Connection abstract class in order
to support CreateConnection() method of Factory Design Pattern
UIU Week 1, CSE 6087 10/19
36. • The above Factory class is used as follows:
• Now have a look how Factory Design Pattern provides the solution.
o Step 1: Abstract class of the class that Factory creates
o Step 2: All derived classes of the abstract class.
UIU Week 1, CSE 6087 11/19
37. o Step 3: The following way you can test the above factory design pattern.
UIU Week 1, CSE 6087 12/19
38. • So the idea here is that the code which changes a lot when design changes (in our
case CreateConnection()), extract that code and put into a Factory class and that
Factory is responsible to create objects.
4. The Value Object Pattern
.
• The intent of this pattern is to provide the way to implement data-types as
immutable classes so that their instances can be handled like built-in values. It is
architectural pattern.
• A value object is a small simple object, like a money or date range, whose
equality is not based on identity.
• You can have multiple copies of an object that represents the date 16 Jan 1998.
Any of these copies will be equal to each other. For a small object such as this, it
is often easier to create new ones and move them around rather than rely on a
single object to represent the date.
• A reference object is an object whose equality is based on its identity. Reference
objects are big in size e.g. customer, order etc.
• A general heuristic is that value objects should be entirely immutable. If you want
to change a value object you should replace the object with a new one and not be
UIU Week 1, CSE 6087 13/19
39. allowed to update the values of the value object itself - updatable value objects
lead to aliasing problems.
• In n-tier software architecture value object pattern is applied when data is
transferred from database to VO (value object tier).
Example
Consider a tool box class in php which carries only nails.
//ToolBox.php
class ToolBox
{
private $_nails;
public function getNails()
{
return $this->_nails;
}
public function setNails(Nails $nails)
{
$this->_nails = $nails;
}
}
//Nails.php
class Nails
{
private $_quantity;
public function __construct($quantity)
{
$this->_quantity = (int) $quantity;
}
UIU Week 1, CSE 6087 14/19
40. public function add(Nails $nails)
{
$this->_quantity += $nails->count();
}
public function count()
{
return $this->_quantity;
}
private function __toString()
{
return (string) $this->_quantity;
}
}
//testtoolBox.php
$myToolBox = new ToolBox;
$yourToolBox = new ToolBox;
//Using twenty Nails
$twentyNails = new Nails(20);
//Start out with equal number of nails.
$myToolBox->setNails($twentyNails);
$yourToolBox->setNails($twentyNails);
//Here's another 100 nails.
$yourToolBox->getNails()->add(new Nails(100));
echo "Your nails: {$yourToolBox->getNails()}<br/>";
echo "My nails: {$myToolBox->getNails()}<br/>";
You probably already noticed that problem is that we are both using the same Nails
object. In this case the problem may be easy to spot and avoid, but as your application
becomes bigger, preventing this type of mishap can save you a huge headache. Another
mayor benefit of using Value Objects is they enable you to encapsulate type-specific
operations. Martin Fowler does a great job at demonstrating this with his Money pattern,
which encapsulates the handling of rounding currency.
UIU Week 1, CSE 6087 15/19
41. The key to creating Value Objects is making them immutable. Because Value Objects’
equality don’t depend on their identity, simply creating a new object when the value
changes, accomplishes this using the following code:
public function add(Nails $nails)
{
return new Nails($this->_quantity + $nails->count());
}
//Here's another 100 nails.
$yourToolBox->setNails(
$yourToolBox->getNails()->add(new Nails(100))
);
Lab Exercise
• Given the following code, complete the code for a BoatFactory class so it can be
used to create big and small boat objects:
public interface Boat {
int maxCapacity;
int topSpeed( )
}
class CruiseShip implements Boat { // big boat
int topSpeed( ) { return 20; }
}
class SpeedBoat implements Boat { // small boat
int topSpeed( ) { return 40; }
}
Boat myBigBoat = BoatFactory.
Boat mySmallBoat = BoatFactory.create(“small”);
public class BoatFactory {
static Boat create(String s) {
// your code here
if (s.equals(“big”))
return new CruiseShip( );
UIU Week 1, CSE 6087 16/19
42. else if (s.equals(“small”))
return new SpeedBoat( );
else
return null; // error
}
}
• Using the same code, use the Decorator design pattern to
i. Add a BoatDecorator class implementing the Boat interface
public class BoatDecorator implements Boat {
Boat b;
BoatDecorator (Boat b) { this.b = b; }
int topSpeed( ) { return b.topSpeed( ); }
}
ii. Create two BoatDecorators withBarnacle( ) and withTurboEngine( ) that
change the result returned by topSpeed( ) by –1 and +10, respectively
public class withBarnacle( ) extends BoatDecorator {
int topSpeed( ) { return b.topSpeed( ) - 1; }
}
public class withTurboEngine( ) extends BoatDecorator {
int topSpeed( ) { return b.topSpeed( ) + 10; }
}
Design Problem – Home work
Background
You are working as part of team which is tasked with designing a security package. The
package is to be used as part of a university system to control access to system services.
The access control policy is based on the role a particular user plays. There are three
roles: Lecturer, Student, and Administrator. Table 1 presents the access rights for each role.
Administrator Student Lecturer
Install software *
Access network * * *
Submit coursework solution *
Publish coursework problem *
UIU Week 1, CSE 6087 17/19
43. Table 1 Access privileges
A member of your team has proposed an initial design which is shown in Figure 1. With
this design, the abstract superclass Operator is intended to be sub-classed with concrete
classes representing particular roles. The Operator class provides a default implementation
of the isAuthorizedTo() method which simply returns false. The concrete subclasses
override this method and depending on the String argument value, return true or false
indicating whether instances of the class have permission to do what is described by the
String argument. For example, calling isAuthorisedTo() with the argument “install software”
on an Administrator instance would return true; calling the method with the same argument
on a Student or Lecturer object would return false.
Figure 1 Initial design
The proposed design, however, suffers from a fundamental weakness. Within the
University, a single individual may play several roles. For example, one person might
play the Lecturer role and teach undergraduate students. The same person might also be
studying part time for a postgraduate degree. In this case, the person will require access
rights for both publishing coursework and submitting coursework. With the existing
design, a person can only be represented by an instance of one of the three concrete
subclasses and is therefore constrained to play a single role.
You raise this problem with your team. Another member responds and points out that the
problem is easily solved by creating additional subclasses to cater for all the
combinations of roles. Specifically, this means defining 3 additional subclasses:
LecturerAndStudent, LecturerAndAdministrator, and StudentAndAdministrator. To cater for an
individual playing all three roles, a further subclass LecturerAndStudentAndAdministrator
would be required.
You think about this suggestion for a moment and it doesn’t take you long to see that it’s
unattractive. First, it would be error-prone to maintain since if the access rights change
for one role, you will have to edit the source files for four classes. For example, adding a
new privilege for students, such as allowing them access to file sharing services (likely to
be used for sharing music files!) would involve editing the Student, LecturerAndStudent,
UIU Week 1, CSE 6087 18/19
44. StudentAndAdministratorand LecturerAndStudentAndAdministrator classes. It then occurs to
you that the problem would be exacerbated if at a later date you wanted to introduce a
new role, such as Secretary. To cater for all possible combinations now would require
many more subclasses. And what if further new roles needed to be accommodated after
that? Clearly the exponential growth in the number of concrete subclasses is
unmanageable.
You air your thoughts to your team members. They are impressed by your analysis but
look to you for a solution. You quickly consider each of the design patterns you know
about, but none of them seem to tackle this seemingly generic problem. A brief search on
the Internet using Google with the terms “subclass explosion” and “design pattern”
returns a host of links which have in common the Decorator design pattern. The
Decorator pattern looks promising …
The task
Investigate the Decorator design pattern and apply it to develop an alternative design to
the access control problem. Your design should address the problems inherent in the
original design. The exam question will assess your understanding and application of the
pattern and thus requires that you do the necessary preparatory work prior to the exam.
*************** End of Week 2 **************
UIU Week 1, CSE 6087 19/19
45. United International University
Trimester: Fall 2012
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof.. S M Monzurur Rahman (mrahman99@yahoo.com)
Week 3: The Observer Design Pattern, The Singleton Design Pattern, The Adapter
Design Pattern
5. The Observer Design Pattern
• Behavioral Pattern – The problem deals with “How can you alert (potentially)
many objects when a certain object’s state changes? Is there a scheme that’s
dynamic—one that allows interconnections to come and go as a script executes?
• The observer pattern is a software design pattern in which an object (called the
subject object) maintains a list of its dependents (called observers) and notifies
them automatically of any state changes, usually by calling one of their methods.
It is mainly used to implement distributed event handling systems.
Example
• The Observer pattern defines an one-to-many dependency between a subject
object and any number of observer objects so that when the subject object
changes state, all its observer objects are notified and updated automatically.
• The Observer pattern essentially allows an unlimited number of objects to
observe or listen to events in the observed object (or subject) by registering
themselves. After observers are registered to an event, the subject will notify
them when the event is fired.
• The subject handles this by storing an observer collection and iterating
through it when the event occurs in order to notify each observer.
• Observer Pattern registers observers with a subject.
UIU Week 3, CSE 6087 1/15
46. • You might have multiple observers. Subject must keep a list of registered
observers and when event occurs it fires (provides notification) all registered
observers.
• Unregister also possible when we do not need any observer.
UIU Week 3, CSE 6087 2/15
47. UML class diagram
The following is class diagram of an observer pattern (Kremer 1998):
Subject
Knows it observers
Has any number of observer
Provides an interface to attach and detaching observer object at run time
Observer
Provides an update interface to receive signal from subject
ConcreteSubject
Store subject state interested by observer
Send notification to it's observer
ConcreteObserver
• Maintain reference to a ConcreteSubject object
• Maintain observer state
• Implement update operation
UIU Week 3, CSE 6087 3/15
48. 6. The Adaptor Design Pattern
• Structural Pattern
• Adapters are used to enable objects with different interfaces to communicate
with each other.
• Convert the interface of a class into another interface clients expect. It is
useful when we upgrade system
• Lets you have an interface class which fits in with a back end class.
• After some time, management upgrades the system and now the back end object
takes Acme object instead of Ace object.
• You can see from the above figure that after upgrade Ace object is not able to
plug into Backend object any more.
• So what do you do - you put an adaptor class in between interface and back end.
The adaptor helps interface to communicate with back end class i.e. adaptor
adapts one object to another receptacle object. This strategy is called adaptor
design pattern.
UIU Week 3, CSE 6087 4/15
49. Example
• Lets we have an example of the adaptor design pattern as follows.
• We need an adaptor because Acme object which fits in with back end and Acme’s
object’s setFirstName and setLastName is supposed to be setName. Similarly,
Acme’s object’s getFirstName and getLastName is supposed to be getName. So,
we need an adaptor or converter to convert Ace object to Acme Object.
• In order to code the above we first code AceInterface and AceClassas follows.
AceClass is based on AceInterface.
UIU Week 3, CSE 6087 5/15
50. • Next we code AcmeInterface and AcmeClassas follows. AcmeClass is based on
AcmeInterface.
UIU Week 3, CSE 6087 6/15
51. • Next we need to code AceToAcmeAdaptor and the code is as follows. The
construct of such class is as follows. Not that it accepts AceClass object in the
constructor and through adaptor it connects to AcmeClass.
• The code for such adaptor is
UIU Week 3, CSE 6087 7/15
52. • Now, we are going to do test the adaptor class. This is done through a test
program and it is given as follows.
• The output of the above test program is as follows:
UIU Week 3, CSE 6087 8/15
53. 7. The Singleton Design Pattern
• Creational Pattern- Ensure a class only has one instance, and provide a global
point of access to it.
• Sometimes we want just a single instance of a class to exist in the system. For
example, we want just one window manager. And we want to ensure that
additional instances of the class cannot be created.
Example
• Normally when you have a class and you create many instances of it then you get
many objects e.g.,
• But in the case of singleton design pattern we get one instantiated object for
many calls of getInstance() method instead of new e.g.,
• Example of Singleton Design pattern is implemented in the following database
class. Note that it private constructor. Only getInstance() method is used to create
single instance of the class.
UIU Week 3, CSE 6087 9/15
54. public class Database
{
private static Database singleObject;
private int record;
private String name;
private Database(String n) // Note private
{
name = n;
record = 0;
}
public static Database getInstance(String n) //
instantiation
{
if (singleObject == null){
singleObject = new Database(n);
}
return singleObject;
}
public void editRecord(String operation)
{
System.out.println("Performing a " + operation +
" operation on record " + record +
" in database " + name);
}
public String getName()
{
return name;
}
}
• The testing of the singleton pattern is as follows:
public class TestSingleton
{
public static void main(String args[])
{
Database database;
database = Database.getInstance("products");
System.out.println("This is the " +
database.getName() + " databse.");
database = Database.getInstance("employees");
System.out.println("This is the " +
database.getName() + " databse.");
}
}
UIU Week 3, CSE 6087 10/15
55. • Output. Note that we did not get employees database here because of single
instantiation.
Singleton and multi-threading
• What if two threads concurrently invoke the instance() method? Any problems?
• When more than one threads pass through the get instance method of the single
pattern Database class then both thread see singleObject==null and both of them
create Database object and which is not desirable.
• To avoid concurrency problem we should redesign the following database class as
follows:
public class DatabaseSynchronized
{
private static DatabaseSynchronized singleObject;
private int record;
private String name;
private DatabaseSynchronized(String n)
{
name = n;
record = 0;
}
UIU Week 3, CSE 6087 11/15
56. public static synchronized DatabaseSynchronized
getInstance(String n)
{
if (singleObject == null){
singleObject = new DatabaseSynchronized(n);
}
return singleObject;
}
public void editRecord(String operation)
{
System.out.println("Performing a " + operation +
" operation on record " + record +
" in database " + name);
}
public String getName()
{
return name;
}
}
• The following class can be used to create the Singleton thread.
public class TestSingletonSynchronized implements Runnable
{
Thread thread;
public static void main(String args[])
{
TestSingletonSynchronized t = new
TestSingletonSynchronized();
}
public TestSingletonSynchronized()
{
DatabaseSynchronized database;
database = DatabaseSynchronized.getInstance("products");
thread = new Thread(this, "second");
thread.start();
System.out.println("This is the " +
database.getName() + " database.");
}
public void run()
{
DatabaseSynchronized database =
DatabaseSynchronized.getInstance("employees");
System.out.println("This is the " +
database.getName() + " database.");
}
}
UIU Week 3, CSE 6087 12/15
57. Lab Practice
The code below shows a user list that sends out a message when users are
added. This list is watched by a logging observer that puts out a message when a
user is added. You are supposed to run this program in the lab and understand
observer patter (Do it in C#).
Observer.php
<?php
interface IObserver {
function onChanged($sender, $args);
}
interface IObservable {
function addObserver($observer);
}
class UserList implements IObservable {
private $_observers = array();
public function addCustomer($name) {
foreach( $this->_observers as $obs )
$obs->onChanged( $this, $name );
}
public function addObserver( $observer ) {
$this->_observers []= $observer;
}
}
class UserListLogger implements IObserver {
public function onChanged( $sender, $args ) {
echo( "'$args' notifies UserListLogger <br>" );
}
UIU Week 3, CSE 6087 13/15
58. }
class AuditLogger implements IObserver {
public function onChanged( $sender, $args ) {
echo( "'$args' notifies AuditLogger <br>" );
}
}
$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addObserver( new AuditLogger() );
$ul->addCustomer( "Jack" );
$ul->addCustomer( "John" );
?>
This code defines four elements: two interfaces and two classes. The IObservable
interface defines an object that can be observed, and the UserList implements that
IObserver list defines what it takes to
interface to register itself as observable. The
be an observer, and the UserListLogger implements that IObserver interface.
The observable user list and the user list event logger
If you run this on the command line, you see this output:
'Jack' notifies UserListLogger
'Jack' notifies AuditLogger
'John' notifies UserListLogger
'John' notifies AuditLogger
UIU Week 3, CSE 6087 14/15
59. Home Work - 1
The code given in HomeWork3-1.rar has an adapter design pattern
demonstration. You are supposed to run this program in the lab and understand
observer patter.
Home Work - 2
Imagine you are designing a virtual world in which the following types of objects needed
to be inter-related: lamps, switches, outlets, and rooms. Assume the following semantics
for those objects:
a. A switch is either on or off and there is one switch per room.
b. When a switch is off, none of the outlets in the same room have power, but
when the switch is on all of them do.
c. A lamp may be plugged into exactly one outlet, and an outlet may have 0, 1,
or 2 lamps plugged into it.
d. A lamp is lit when it is plugged into an outlet that has power, and otherwise is
unlit.
Q1. If you used the Observer pattern to relate those objects, please describe everything
that would happen (according to that pattern) when a lamp was plugged into a socket.
Q2. If you used the Observer pattern to relate those objects, please describe everything
that would happen (according to that pattern) when a switch was flipped from off to on.
Home Work - 3
What design pattern should you think of when you want to reuse an object but it has
the wrong interface? Give an example to support your answer.
Home Work - 4
“I am limited to how many database connections I can have. What design pattern helps
me limit the number of objects I can create?”
• You could use Singleton pattern where we only want one instance of the class.
After making the constructor private, you get one version of the class. – Give
example code to support the above.
• You can use the Singleton pattern to limit the number to X as well.- Give example
code to support the above.
*************** End of Week 3 **************
UIU Week 3, CSE 6087 15/15
60. United International University
Trimester: Fall 2012
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof. S M Monzurur Rahman (mrahman99@yahoo.com)
Week 4: Registry design pattern, • Dependency Injection pattern
8. Registry Design Pattern
• Behavioral Pattern – It’s generally considered “good form” to avoid the use of
global variables, objects are usually passed from one code segment to another as
parameters.
• The problem with passing instances globally is that objects sometimes end up as
“tramp data,” passed into one function only to be passed again to another function
which truly needs the object. To make writing, reading, and consuming code
simpler, it’s best to minimize the number of different objects and consolidate
knowledge of how to get to a numerous of other widely-used objects into a single,
well-known object.
• How can you get references to objects through a single, well-known, object? The
Registry design pattern is like an “object phone book”—a directory—that stores
and retrieves references to objects.
• The Registry pattern can be useful, for example, if, for the bulk of your
application, you use the same database connection, but need to connect to an
alternate database to perform a small set of tasks every now and then. If your DB
class is implemented as a Singleton, this is impossible (unless you implement two
separate classes, that is)—but a Registry makes it very easy:
UIU Week 4, CSE 6087 1/6
61. Example
class Registry {
private static $_register;
public static function add(&$item, $name = null)
{
if (is_object($item) && is_null($name)) {
$name = get_class($item);
}
elseif (is_null($name)) {
$msg = "You must provide a name for non-objects";
throw new Exception($msg);
}
$name = strtolower($name);
self::$_register[$name] = $item;
}
public static function &get($name){
$name = strtolower($name);
if (array_key_exists($name, self::$_register)) {
return self::$_register[$name];
}
else {
$msg = "’$name’ is not registered.";
throw new Exception($msg);
}
}
public static function exists($name){
$name = strtolower($name);
if (array_key_exists($name, self::$_register)) {
return true;
}
else {
return false;
}
}
}
UIU Week 4, CSE 6087 2/6
62. // testing is at here
$db = new DB();Registry::add($db);
// Later on
if (Registry::exists(’DB’)) {
$db = Registry::get(’DB’);
}
else {
die(’We lost our Database connection somewhere. Bear with us.’);
}
9. Dependency Injection Pattern
• Behavioral Pattern – It is a technique that indicates to a part of a program which
other parts it can use, i.e. to supply an external dependency, or reference, to a
software component.
• In technical terms, it is a design pattern that separates behavior from
dependency resolution, thus decoupling highly dependent components.
Example
public interface ICar {
public float getSpeed();
public void setPedalPressure(final float PEDAL_PRESSURE);
}
public interface IEngine {
public float getEngineRotation();
public void setFuelConsumptionRate(final float FUEL_FLOW);
}
The following shows a common arrangement with no dependency injection applied:
public class DefaultEngineImpl implements IEngine {
private float engineRotation = 0;
public float getEngineRotation() {
UIU Week 4, CSE 6087 3/6
63. return engineRotation;
}
public void setFuelConsumptionRate(final float FUEL_FLOW) {
engineRotation = …;
}
}
public class DefaultCarImpl implements ICar {
private IEngine engine = new DefaultEngineImpl();
public float getSpeed() {
return engine.getEngineRotation()*…;
}
public void setPedalPressure(final float PEDAL_PRESSURE) {
engine.setFuelConsumptionRate(…);
}
}
public class MyApplication {
public static void main(String[] args) {
ICar car = new DefaultCarImpl();
car.setPedalPressure(5);
float speed = car.getSpeed();
System.out.println("Speed of the car is " + speed);
}
}
In the above example, using the ICar interface, an engine instance is created by using the
IEngine interface in order to perform operations on the car. Hence, it is considered
highly-coupled, because it couples a car directly with a particular engine implementation.
In cases where the DefaultEngineImpl dependency is managed outside of the scope of
the car, the class of the car implementing the ICar interface must not instantiate the
DefaultEngineImpl dependency. Instead, that dependency is injected externally
The following shows a common arrangement dependency injection applied:
public class DefaultCarImpl implements ICar {
private IEngine engine;
public DefaultCarImpl(final IEngine engineImpl) {
engine = engineImpl;
}
public float getSpeed() {
return engine.getEngineRotation()*…;
}
public void setPedalPressure(final float PEDAL_PRESSURE) {
engine.setFuelConsumptionRate(…);
UIU Week 4, CSE 6087 4/6
64. }
}
public class CarFactory {
public static ICar buildCar() {
return new DefaultCarImpl(new DefaultEngineImpl());
}
}
public class MyApplication {
public static void main(String[] args) {
ICar car = CarFactory.buildCar();
car.setPedalPressure(5);
float speed = car.getSpeed();
System.out.println("Speed of the car is " + speed);
}
}
In the example above, the CarFactory class assembles a car and an engine together by
injecting a particular engine implementation into a car. This moves the dependency
management from the DefaultCarImpl class into the CarFactory class. As a
consequence, if the DefaultCarImpl needed to be assembled with a different
DefaultEngineImpl implementation, the DefaultCarImpl code would not be changed.
Framework-managed dependency injection
There are several frameworks available that automate dependency management
by delegating the management of dependencies. Typically, this is accomplished by a
container using XML or "meta data" definitions. Refactoring the above example to use an
external XML-definition framework:
<service-point id="CarBuilderService">
<invoke-factory>
<construct class="Car">
<service>DefaultCarImpl</service>
<service>DefaultEngineImpl</service>
</construct>
</invoke-factory>
</service-point>
/** Implementation not shown **/
public class MyApplication {
public static void main(String[] args) {
Service service =
(Service)DependencyManager.get("CarBuilderService");
ICar car = (ICar)service.getService(Car.class);
car.setPedalPressure(5);
float speed = car.getSpeed();
}
}
UIU Week 4, CSE 6087 5/6
65. In the above example, a dependency injection service is used to retrieve a
CarBuilderService service. When a car is requested, the service returns an appropriate
implementation for both the car and its engine.
Lab Practice
The code given in HomeWork4.rar has a registry design pattern
demonstration. You are supposed to run this program in C# or Java twice in the lab
to understand registry pattern. After first run there will be an object will be created
in object directory. And after second run the object will be retrieved from the file.
Home WOrk
The code given in HomeWork4.rar has a dependency injection design pattern
demonstration. You are supposed to run program yesTest.php and noTest.php to
understand how to use dependency injection pattern.
*************** End of Week 4 **************
UIU Week 4, CSE 6087 6/6
66. United International University
Trimester: Fall 2012
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof. S M Monzurur Rahman (mrahman99@yahoo.com)
Week 5: Facade Design Pattern, Template Design Pattern, Model-View-Controller
10. The Façade Design Pattern
• Structural Pattern
• Provide a unified interface to a set of interfaces in a subsystem.
• Façade defines a higher-level interface that makes the subsystem easier to
use.
• It wraps a complicated subsystem with a simpler interface.
How it works
• Lets we have a difficult interface in one area of code and the other code only takes
simple interface.
• In the above case we use Façade design pattern to establish communication in
between of such code.
UIU Week 5, CSE 6087 1/15
67. Difference between Adapter and Facade
• Adapter pattern
o is used for providing an interface for incompatible classes.i.e Adapter
provides a different interface to its subjects.
o Adapter changes an object's interface and make it usable by another
objects .i.e the Adapter pattern changes the interface of one or more
classes into one interface that a client is expecting.
• Facade provides
o the simpler interface to the client.let us assume u have number of sub
systems and each one has exposed some interfaces.but all interfaces are
not required by the client.so what we do make one interface top of the
subsystems i.e facade.
o In Facade we wraps multiple objects.
o Facade is the simpler interface of the complex sub systems
UIU Week 5, CSE 6087 2/15
68. UML Diagram
As told Façade is seen as the simpler interface of the complex sub systems and the UML
is as follows.
Example
Consider an example of a Library. Where people borrow and returns books.
In our example we have
Facade : Facade
Subsystem classes : Book ,Shelf , Person
class program
{
internal class Book
{
internal string FindBook()
{
return "Subsystem for Book, Method FindBookn";
}
internal string Returned()
{
return "Subsystem for Book, Method Returnedn";
}
}
internal class Shelf
{
internal string AssignBook()
{
return "Subsystem for Shelf, Method AssignBookn";
}
UIU Week 5, CSE 6087 3/15
69. internal string PlaceBook()
{
return "Subsystem for Shelf, Method PlaceBookn";
}
}
internal class Person
{
internal string Return()
{
return "Subsystem For Person, Method Returnn";
}
internal string Borrow()
{
return "Subsystem For Person, Method Borrown";
}
}
public static class Facade
{
static Book book = new Book();
static Shelf shelf = new Shelf();
static Person person = new Person();
public static void ReturnBook()
{
Console.WriteLine("ReturnBook 1n" +
person.Return() +
shelf.PlaceBook()+
book.Returned());
}
public static void BorrowBook()
{
Console.WriteLine("BorrowBook 1n" +
book.FindBook() +
person.Borrow()
);
}
}
static void Main()
{
Facade.BorrowBook(); //two interfaces as described in the
problem before
Facade.ReturnBook();
}
}
Output
UIU Week 5, CSE 6087 4/15
70. Above was very simple demonstration of using a facade design pattern. The role of above
example was to provide an easier interface for different high-level views of subsystems
whose details are hidden from users.Everything in the façade has to be public so that the
Client, which is compiled into a different assembly, can access it. In library example we
have different subsystems and using facade we give very simple interface to client.
Motivation
• Structuring a system into subsystems helps reduce complexity
• Subsystems are groups of classes, or groups of classes and other subsystems
• The interface exposed by the classes in a subsystem or set of subsystems can
become quite complex
• One way to reduce this complexity is to introduce a facade object that provides a
single, simplified interface to the more general facilities of a subsystem
UIU Week 5, CSE 6087 5/15
71. 11. The Template Design Pattern
• Behavioral Pattern
• It is used to set up the outline or skeleton of an algorithm (a sequence of
actions), leaving the details to specific implementations later. This way,
subclasses can override parts of the algorithm without changing its overall
structure.
• The Template Design Pattern is perhaps one of the most widely used and
useful design pattern.
Example
• In Template Design Pattern you will have a base class and that will have a
template method which is go in the following example. The template method will
have series of methods which make the outline of an algorithm. The inheriting
classes may override the methods which are in the template method. The template
method is final one.
UIU Week 5, CSE 6087 6/15
72. • In the above example we create robots using the template go method. We may
create car robot and cookie robot using the above template design pattern. The
code is as follows.
• At first make the abstract class as our base class.
public abstract class RobotTemplate {
public final void go() {
start();
getParts();
assemble();
test();
stop();
}
public void start() {
System.out.println("Starting....");
}
public void getParts() {
System.out.println("Getting parts....");
}
public void assemble() {
System.out.println("Assembling....");
}
public void test() {
System.out.println("Testing....");
}
public void stop() {
System.out.println("Stopping....");
}
}
• Next two inheriting classes. Here overriding methods are provided for specific
robot building.
public class AutomotiveRobot extends RobotTemplate
{
private String name;
public AutomotiveRobot(String n)
{
name = n;
}
public void getParts()
{
System.out.println("Getting a carburetor....");
}
UIU Week 5, CSE 6087 7/15
73. public void assemble()
{
System.out.println("Installing the carburetor....");
}
public void test()
{
System.out.println("Revving the engine....");
}
public String getName()
{
return name;
}
}
public class CookieRobot extends RobotTemplate
{
private String name;
public CookieRobot(String n)
{
name = n;
}
public void getParts()
{
System.out.println("Getting a flour and sugar....");
}
public void assemble()
{
System.out.println("Baking a cookie....");
}
public void test()
{
System.out.println("Crunching a cookie....");
}
public String getName()
{
return name;
}
}
• In the last we provide test program to test the template.
public class TestTemplate
UIU Week 5, CSE 6087 8/15
74. {
public static void main(String args[])
{
AutomotiveRobot automotiveRobot =
new AutomotiveRobot("Automotive Robot");
CookieRobot cookieRobot = new CookieRobot("Cookie
Robot");
System.out.println(automotiveRobot.getName() + ":");
automotiveRobot.go();
System.out.println();
System.out.println(cookieRobot.getName() + ":");
cookieRobot.go();
}
}
Customizing – Conditional Template
• You can provide conditional methods in the template method of the base class so
that algorithm does not need to take all the methods. Example is given as follows.
Here testOK() method controls whether we need or not test() method.
public abstract class RobotHookTemplate
{
public final void go()
{
UIU Week 5, CSE 6087 9/15
75. start();
getParts();
assemble();
if (testOK()){
test();
}
stop();
}
public void start()
{
System.out.println("Starting....");
}
public void getParts()
{
System.out.println("Getting parts....");
}
public void assemble()
{
System.out.println("Assembling....");
}
public void test()
{
System.out.println("Testing....");
}
public void stop()
{
System.out.println("Stopping....");
}
public boolean testOK()
{
return true;
}
}
• CookieRobotHook which do not need test() method.
public class CookieHookRobot extends RobotHookTemplate
{
private String name;
public CookieHookRobot(String n)
{
name = n;
}
public void getParts()
{
System.out.println("Getting a flour and sugar....");
}
UIU Week 5, CSE 6087 10/15
76. public void assemble()
{
System.out.println("Baking a cookie....");
}
public String getName()
{
return name;
}
public boolean testOK()
{
return false;
}
}
12. Model-View-Controller Design Pattern
• Architectural design pattern
• Model-View-Controller (MVC) is a classic design pattern often used by
applications that need the ability to maintain multiple views of the same data.
• The MVC pattern hinges on a clean separation of objects into one of three
categories — models for maintaining data, views for displaying all or a portion of
the data, and controllers for handling events that affect the model or view(s).
• MVC is a pattern to decouple your UI (presentation layer) from your model
(domain layer). Layering is an approach to decouple subsystems in general (and
much more). MVC is basically a recipe to enable proper layering.
How It Works
The MVC abstraction can be graphically represented as follows. Events typically cause a
controller to change a model, or view, or both. Whenever a controller changes a model’s
data or properties, all dependent views are automatically updated. Similarly, whenever a
controller changes a view, for example, by revealing areas that were previously hidden,
the view gets data from the underlying model to refresh itself.
UIU Week 5, CSE 6087 11/15
77. 3-tier Multi-tier Architecture
Example
We explain the MVC pattern with the help of a simple spinner component which
consists of a text field and two arrow buttons that can be used to increment or decrement
a numeric value shown in the text field.
UIU Week 5, CSE 6087 12/15
78. • The spinner’s data is held in a model that is shared with the text field.
• The text field provides a view of the spinner’s current value.
• Each button in the spinner attached to an action listener that eventually handles
that event. Depending on the source of the event, the ultimate action listener
either increments or decrements the value held in the model. The action listener is
an example of a controller.
The trampolines that initially receive the action events fired by the arrow buttons, are also
controllers — However, instead of modifying the spinner’s model directly, they delegate
the task to a separate controller (action listener).
Lab Exercise MVC VS MVP
In MVP, the Presenter contains the UI business logic for the View. All invocations from
the View delegate directly to Presenter. The Presenter is also decoupled directly from the
View and talks to it through an interface. This is to allow mocking of the View in a unit
test. One common attribute of MVP is that there has to be a lot of two-way dispatching.
For example, when someone clicks the "Save" button, the event handler delegates to the
Presenter's "OnSave" method. Once the save is completed, the Presenter will then call
back the View through its interface so that the View can display that the save has
completed. The key differences between the patterns:
MVP Pattern
• View is more loosely coupled to the model. The presenter is responsible for
binding the model to the view.
• Easier to unit test because interaction with the view is through an interface
UIU Week 5, CSE 6087 13/15
79. • Usually view to presenter map one to one. Complex views may have multi
presenters.
MVC Pattern
• Controller are based on behaviors and can be shared across views
• Can be responsible for determining which view to display
MVP the View is in charge.
The View, in most cases, creates it's Presenter. The Presenter will interact with the model and
manipulate the View through an interface. The View will sometimes interact with the Presenter,
usually through some interface. This comes down to implementation, do you want the View to call
methods on the presenter or do you want the View to have events the Presenter listens to. It boils
down to this: The View knows about the Presenter. The View delegates to the Presenter.
MVC the Controller is in charge.
Controller is created or accessed based on some event/request, the controller then interacts with
the Model to further configure the View. It boils down to: Controller creates and manages View,
View is slave to Controller. View does not know about Controller.
An example of MVC and MVP is provided in MVC-MVP.rar
UIU Week 5, CSE 6087 14/15
80. HW-1
HW-2
HW-3
ABC Company stored data about employees (e.g., name, age, address) in two
areas - one is in an excel file (abc.xls) and the other is in a text file (abc.txt). You are
hired to write a program to process ABC’s employees. Here process means – reading data
from file and printing names of each file. Write a program (in java or C#) using template
design pattern for ABC to process employees’ data.
Hints: You need one abstract class where process template method exists and two sub
classes – one for text file processing and the other is excel file processing. The process
template method shall contain two steps – readData() and printData().
*************** End of Week 5 **************
UIU Week 5, CSE 6087 15/15
81. United International University
Trimester: Fall 2012
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof. S M Monzurur Rahman (mrahman99@yahoo.com)
Week 6: Mid Exam
*************** End of Week 6**************
UIU Week 7, CSE 6087 1/1
82. United International University
Trimester: Fall 2012
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof. S M Monzurur Rahman (mrahman99@yahoo.com)
Week 7: Enterprise Pattern, SOAP, Multitier Architecture
Enterprise Design Pattern
• Design patterns which are used mostly for Enterprise Application Architecture are
known as Enterprise Design Pattern.
• Enterprise Design patterns are introduced in Core J2EE Patterns, the patterns deal with
presentation, and application logic.
Examples of Enterprise design Pattern
Base Patterns
Command: - An object encapsulates everything needed to execute a method in another
object
Registry: This pattern is useful for making data available to all classes in a process.
Through careful use of serialization, it can also be used to store information across a
session or even across instances of an application.
Web Presentation Patterns:
Front Controller: A controller that handles all requests for a Web site.
Application Controller: A centralized point for handling screen navigation and the flow
of an application
Template View: Renders information into HTML by embedding markers in an HTML
page.
Page Controller: An object that handles a request for a specific page or action on a Web
site. Lighter weight but less flexible than Front Controller, Page Controller addresses
the same need. Use this pattern to manage requests and handle view logic if you want
fast results and your system is unlikely to grow substantially in complexity.
UIU Week 7, CSE 6087 1/29
83. Domain Logic Patterns
Transaction Script When you want to get things done fast, with minimal up-front
planning, fall back on procedural library code for your application logic. This pattern
does not scale well. This pattern Organizes business logic by procedures where each
procedure handles a single request from the presentation.
Domain Model: An object model of the domain that incorporates both behavior and data.
13. Command Design Pattern
• Behavioural Pattern -An object encapsulates everything needed to execute a
method in another object
• When two objects communicate, often one object is sending a command to
the other object to perform a particular function. The most common way to
accomplish this is for the first object (the "issuer") to hold a reference to the
second (the "recipient"). The issuer executes a specific method on the
recipient to send the command.
Example
• Let we have two set of objects i.e. command issuer and receiver as follows.
Crisis centre issues command to the server to keep it up. There are set
UIU Week 7, CSE 6087 2/29
84. commands which crisis centre can execute on servers. Command design pattern
work on this example.
Set of commands forms command object in crisis centre which communicate to
servers. Such objects are shown below.
Servers are called receivers and Crisis centre is called invoker here. Coding starts
with the interface of receiver as follows.
public interface Receiver
{
public void connect();
public void diagnostics();
public void reboot();
public void shutdown();
public void disconnect();
}
Servers implements the interface as follows.
UIU Week 7, CSE 6087 3/29
85. public class AsiaServer implements Receiver
{
public AsiaServer()
{
}
public void connect()
{
System.out.println("You're connected to the Asia server.");
}
public void diagnostics()
{
System.out.println("The Asia server diagnostics check out OK.");
}
public void shutdown()
{
System.out.println("Shutting down the Asia server.");
}
public void reboot()
{
System.out.println("Rebooting the Asia server.");
}
public void disconnect()
{
System.out.println("You're disconnected from the Asia server.");
}
}
public class EuroServer implements Receiver
{
public EuroServer()
{
}
public void connect()
{
System.out.println("You're connected to the Euro server.");
}
public void diagnostics()
{
System.out.println("The Euro server diagnostics check out OK.");
}
public void shutdown()
{
System.out.println("Shutting down the Euro server.");
}
public void reboot()
{
UIU Week 7, CSE 6087 4/29
86. System.out.println("Rebooting the Euro server.");
}
public void disconnect()
{
System.out.println("You're disconnected from the Euro server.");
}
}
public class USServer implements Receiver
{
public USServer()
{
}
public void connect()
{
System.out.println("You're connected to the US server.");
}
public void diagnostics()
{
System.out.println("The US server diagnostics check out OK.");
}
public void shutdown()
{
System.out.println("Shutting down the US server.");
}
public void reboot()
{
System.out.println("Rebooting the US server.");
}
public void disconnect()
{
System.out.println("You're disconnected from the US server.");
}
}
Interface for command is as follows.
public interface Command
{
public void execute();
public void undo();
}
All commands implementations are as follows.
public class ShutDownCommand implements Command
UIU Week 7, CSE 6087 5/29
87. {
Receiver receiver;
public ShutDownCommand(Receiver r)
{
receiver = r;
}
public void execute()
{
receiver.connect();
receiver.shutdown();
receiver.disconnect();
System.out.println();
}
public void undo()
{
System.out.println("Undoing...");
receiver.connect();
receiver.reboot();
receiver.disconnect();
System.out.println();
}
}
public class RunDiagnosticsCommand implements Command
{
Receiver receiver;
public RunDiagnosticsCommand(Receiver r)
{
receiver = r;
}
public void execute()
{
receiver.connect();
receiver.diagnostics();
receiver.disconnect();
System.out.println();
}
public void undo()
{
System.out.println("Can't Undo.");
System.out.println();
}
}
public class RebootCommand implements Command
{
Receiver receiver;
public RebootCommand(Receiver r)
UIU Week 7, CSE 6087 6/29
88. {
receiver = r;
}
public void execute()
{
receiver.connect();
receiver.reboot();
receiver.disconnect();
System.out.println();
}
public void undo()
{
System.out.println("Undoing...");
receiver.connect();
receiver.shutdown();
receiver.disconnect();
System.out.println();
}
}
At last step we create invoker to test our command design pattern. Invoker loads
commands.
public class Invoker
{
Command commands[] = new Command[5];
int position;
public Invoker()
{
position = -1;
}
public void setCommand(Command c)
{
if (position < commands.length - 1){
position++;
commands[position] = c;
} else {
for (int loopIndex = 0; loopIndex < commands.length - 2;
loopIndex++){
commands[loopIndex] = commands[loopIndex + 1];
}
commands[commands.length - 1] = c;
}
}
public void run()
{
commands[position].execute();
}
UIU Week 7, CSE 6087 7/29
89. public void undo()
{
if (position >= 0){
commands[position].undo();
}
position--;
}
}
The testing of the above command design pattern is as follows:
public class TestCommands
{
public static void main(String args[])
{
TestCommands t = new TestCommands();
}
public TestCommands()
{
Invoker invoker = new Invoker();
// Create the receivers
AsiaServer asiaServer = new AsiaServer();
EuroServer euroServer = new EuroServer();
USServer usServer = new USServer();
//Create the commands
ShutDownCommand shutDownAsia = new ShutDownCommand(asiaServer);
RunDiagnosticsCommand runDiagnosticsAsia = new
RunDiagnosticsCommand(asiaServer);
RebootCommand rebootAsia = new RebootCommand(asiaServer);
ShutDownCommand shutDownEuro = new ShutDownCommand(euroServer);
RunDiagnosticsCommand runDiagnosticsEuro = new
RunDiagnosticsCommand(euroServer);
RebootCommand rebootEuro = new RebootCommand(euroServer);
ShutDownCommand shutDownUS = new ShutDownCommand(usServer);
RunDiagnosticsCommand runDiagnosticsUS = new
RunDiagnosticsCommand(usServer);
RebootCommand rebootUS = new RebootCommand(usServer);
invoker.setCommand(shutDownAsia);
invoker.run();
invoker.setCommand(rebootAsia);
invoker.run();
invoker.undo();
invoker.undo();
}
}
UIU Week 7, CSE 6087 8/29
91. The classes and/or objects participating in this pattern are:
Command(Command)
• declares an interface for executing an operation
ConcreteCommand (ServerCommand)
• defines a binding between a Receiver object and an action
• implements Execute by invoking the corresponding operation(s) on Receiver
Client (CommandApp)
• creates a ConcreteCommand object and sets its receiver
Invoker (User)
• asks the command to carry out the request
Receiver (Server)
• knows how to perform the operations associated with carrying out the request.
Multi-tier Computing
• The J2EE platform is an implementation of the concept of Multi-tie computing.
• Multi-tier is a distributed software architecture in which systems are divided into
autonomous processes, where a client sends requests to a server and that server
sends responses as an answer to the request to that client.
• Multi-tier is a concept that will distribute the autonomous processes over clients
and servers, based on the suitability for the task of those clients and servers.
Figure : Client/Server roles
UIU Week 7, CSE 6087 10/29
92. • As can be seen clearly from the figure above, it is possible that a server can
be the client of another server. In general there is no clear distinction
between clients and server besides a concrete request.
• In a large distributed system almost every client is a server and every server
is also a client.
14. Multi-tier logical layering
• In Multi-tier computing software are divided in logical layers.
• A layer is a reusable portion of code that performs a specific function.
• Each layer in the software is responsible for a specific task in the application.
The logical layering of an application does not need to be the same as the
physical layering of an application.
Example
In theory we distinguish 6 layers in software, as shown in figure below.
Figure : Software layering
UIU Week 7, CSE 6087 11/29