0% found this document useful (0 votes)
419 views1,281 pages

哈工大设计模式课件(孙玉山)

Uploaded by

slowdownfu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
419 views1,281 pages

哈工大设计模式课件(孙玉山)

Uploaded by

slowdownfu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1281

Introduction to Software Architecture

Professor:
Yushan (Michael) Sun
Fall 2016

163邮箱(存放讲稿+提交大作业):
User: 18906317629
Password: ruanjian
Introduction to Software Architecture

建筑设计的例子1

典型欧式建筑图片1
Introduction to Software Architecture

建筑设计的例子3

中式宫廷建筑
Introduction to Software Architecture

房屋设计的例子1

一个只有一个房间的房子-建造成本低,但是居住不方便
Introduction to Software Architecture

房屋设计的例子2

Kitchen Dining-room Bathroom

Studyroom
客厅(living room)
Bedroom1 Bedroom2


一个有许多房间的房子-建造成本高,但是方便居住
Introduction to Software Architecture

• 问题:假如你要用Java语言开发一个程序,
怎样进行软件设计?

• 你可能的回答:
a) 不用设计,直接写代码呗
b) 将程序设计成一个单独的类
c) 将程序设计成若干个类
Introduction to Software Architecture

二手车拍卖系统程序设计的例子
JPanel

CarAuctionGUI
+getSelectedCar(): String //get user input
+getBitPrice(): String //get user input bit price
+extractCarList(): String[] //display car list
+setUpCarList(JComboBox cmbCarList,String[] carList) //add car list onto cmbCarList
+constructCarFileUrl(String carChosen): URL //produce an UML based on car name
+updateCarDescription(JEditorPane editorPane, URL url) //update car description
+showBitPrice(JTextArea bitShownText, String price ) display bit price
+produceCarImaIcon(String carChosen): ImageIcon //produce image icon for car
+updateCarPicture(JLabel imgLabel,ImageIcon imgIcon) //update car picture
#createImageIcon(String path): ImageIcon

二手车拍卖系统的类图设计-单独一个类的情况
CarAuctionGUI Controller
getSelectedCar():String -objCarGUI:CarAuctionGUI
getBitPrice():String -cm: CarModel
-civ: CarGUIView
getCarList():String[]
-cb: CarBitView
setUpComboBox(String[] carList):void -carPrice: String
-private String[] carList
<<interface>> actionPerformed(ActionEvent e): void
Observable
+register(Observer obs):void <<interface>>
+notifyObservers(): void
Observer
update(Observable subject): void
CarModel
-String[] carNameList;
-String bitPrice;
CarGUIInfoView
+setCarList(String[] cars):void
+getCarList(): String[] -model: CarModel
+setSelectedCar(String sCar): void -imagePane: JScrollPane
+getSelectedCar(): String +update(): void
+setBitPrice(String bPrice): void
+getBitPrice(): String CarBitInfoView
+setCarFileURL(): void
-model: CarModel
+getCarFileURL(): URL
-bitText: JTextArea
+setupImageIcon(): void
+getImageIcon(): ImageIcon +update(): void
+register(Observer obs):void
+notifyObservers(): void 应用MVC模式的二手车拍卖系统的类图设计
Introduction to Software Architecture

二手车拍卖系统用户图形界面
Question: which design is better?
Introduction to Software Architecture

• 软件设计要考虑很多因素:
– 模块化(modularization)
– 可扩展性 (extensibility)
– 性能 (performance)
– 安全 (security)
• 软件设计要借鉴成功经验
– 软件设计模式 (software design patterns)
– 软件体系结构 (software architecture)
Introduction to Software Architecture

1. Why should we learn this course?


学习本课程的目的
1. To use software design patterns in your own
design of classes
– To be a successful software developer or
software architect
2. To use software architecture in your own
design of programs or a software systems
– To be a successful software architect or
software developer
Introduction to Software Architecture

Question: What is a design pattern?

Definition of a pattern (软件设计模式的定义):


“A pattern addresses a recurring design problem
that arises in specific design situations and
presents a solution to it”.
“一个模式处理一个特定设计情况下反复提出的设计问
题,并且为其提供一个解决方案”
(Buschmann, et. al. 1996)
Introduction to Software Architecture

Why use software patterns (为什么使用设计模式)?


Ø 学习专家经验. Design Patterns capture expertise and
make it accessible to non-experts in a standard form.
Ø 为了交流. Design Patterns facilitate communication
among developers by providing a common language.
Ø 为了重复利用成功的设计. Design Patterns make it
easier to reuse successful designs and avoid
alternatives that diminish reusability.
Ø 提供设计修改. Design Patterns facilitate design
modifications.
Introduction to Software Architecture

Definition of Software Architecture


• Definition (软件体系结构的定义):
The software architecture of a program or
computing system is the structure or structures of
the system, which comprise
– software components,
– the externally visible properties of those
components, and
– the relationships among them. [Bass 98]
Introduction to Software Architecture
软件体系结
构的例子1

Architecture of an Integrated Software Development


Environment
Introduction to Software Architecture
软件体系结构的例子2

Java EE Architecture
Introduction to Software Architecture

Three reasons why SA is important to large,


complex, software-intensive systems.

1. SA是交流工具。It is a vehicle for


communication among stakeholders.
Introduction to Software Architecture

2. 最早的设计决策的代表。It is the representation


of the earliest design decisions. It shows the
tradeoffs (折衷,权衡)
– between performance and security,
– between maintainability and reliability, and
– between the cost of the current development
effort and the cost of future developments in
the architecture.
Introduction to Software Architecture

3.It is a reusable, transferable abstraction of a


system. (一个系统的可重复利用的,可转移的抽象)
It
Øcan be applied to other systems exhibiting
similar requirements and
Øcan promote large-scale reuse and software
product lines.
Introduction to Software Architecture

What to cover in this course?

• Design patterns: 14 hours


– 10 design patterns will be taught
• Software architecture:14 hours
– 9 software architectures will be taught
Introduction to Software Architecture

• Pre-courses: Software engineering, C++


or Java. In this class, we use
language Java
• Reference Textbooks:
Ø《软件设计模式与体系结构》,孙玉山,高等
教育出版社,2013年5月出版;
ØPartha Kuchana, “Software architecture
design patterns in Java”, CRC Press LLC,
2004;
ØMary Shaw and David Garlan, “Software
Architecture: Perspectives on an Emerging
Discipline”。
Introduction to Software Architecture

其它参考书与材料(Reference books)

[1] Gamma, Helm, Johnson and Vlissides, “Design


Patterns: Elements of Reusable Software”,
1995
[2] James W. Cooper, “The design patterns, Java
Companion”, 1998
[3] Analysis Patterns: Reusable Object Models,
Martin Fowler, Addison-Wesley, 1997
[4] Java 与模式,阎宏,电子工业出版社,2005,4
[5] Paul Clements, “Software product lines:
practices and patterns”.
Introduction to Software Architecture

作业与项目
Homework and projects: 40%;
– Homework: 2 homework:
• 10 points per each (代码编写、回答问题)
– Project: 1 project
• 20 points (代码编写、回答问题)

期末考试
Final test (open-book): 60%;
Software Architecture
软件体系结构

Professor:
Yushan (Michael) Sun
Fall 2016
Year period
1959),
1958),
1968 1972

(Top-Down Design)

1983)
OO Design
1995
Language history
• In 1949, the language appeared
– need to change program statements into 0's
and 1's by hand.
• In 1957, , was designed at IBM for
scientific computing.
– IF, DO, and GOTO statements,
– good at handling numbers,
– bad at handling input and output
• In 1959, , for business use.
– data types: numbers and strings of text.
– In COBOL, program is built in 4 or 5 major
sections
– Still in used in banking/financial systems
• In 1958, ,for Artificial Intelligence
research.
– only data type: list,
– denoted by a sequence of items enclosed by
parentheses (‘a’, ‘c’, ‘d’)
– recursive calling of functions
• In 1958, Algol, for scientific use.
– recursive (递归) calling of functions,
– the root of the tree that has led to Pascal, C,
C++, and Java.
• 1968, for teaching.
– combined many of the best features of the
languages in use at the time, COBOL,
FORTRAN, and ALGOL.
– Programmers liked this language
– Pascal also improved the "pointer" data type.
• 1972, was developed, at Bell Labs in New
Jersey.
– All of the features of Pascal, including the
new ones such as the CASE statement
– uses pointers extensively
– fast and powerful at the expense of being
hard to read.
Dennis Ritchie
1941-2011
Father of Unix and C

Ritchie got Ph.D (in physics, mathematics) from Harvard


University
Brief history of C and Unix (developed by AT&T Bell
Labs)
ØC was developed by Dennis Ritchie between
1969 and 1973
ØUnix operating system was developed in 1969
by Ken Thompson, Dennis Ritchie, etc., 6
people
ØThe Unix operating system first developed in
assembly language(汇编语言), had been
almost entirely recoded in C in 1973
Ken Thompson
Dennis Ritchie

• They received awards together:


• In 1983, the Turing Award for the UNIX operating
system;
• In 1990, the IEEE Richard W. Hamming Medal;
• In 1997, Fellows of the Computer History Museum;
• In 1999, the National Medal of Technology of
1998 from President Clinton
Brief History of Microsoft

• Microsoft was founded by Bill Gates and


Paul Allen on April 4, 1975
Ø第一桶金:to develop and sell BASIC
interpreters for Altair 8800
1969年发射的Apollo 11 号控制系统
a) Use real time operating system, for astronauts
Apollo to control the Apollo 11
Guidance b) Memory:64Kbyte; CPU: 0.043MHz
Computer c) The AGC program Luminary was coded in Mac
(飞船载) language (MIT Algebraic Compiler)
d) Program translated into assembler
language program (punch cards)input into
AGC

a) IBM said the 6MB program it developed, to


monitor the spacecraft’s environmental and
IBM astronauts' biomedical data, was the most
System/360 complex software ever written
Model 75s b) The reentry guidance program for Apollo was
(地面站) written in FORTRAN and required 4,000
punched cards
32 years old
• In 1983, was released.
– to organize the raw power of C using OOP,
but maintain the speed of C and be able to
run on many different types of computers.
– most often used in simulations, such as
games.
– provides an elegant way to track and
manipulate hundreds of objects
• In 1995, 20 years old
• Netscape licensed for use in their
internet browser, Navigator.
• So, Java became the language of the future
and several companies announced
applications which would be written in
Java.
• All the program code are written in a single
Continuous main program.
• Program written in unstructured language usually
contains a series of statements.
• One line contains one statement, with a number
label to denote the line number to allow the program
execution can jump (use GOTO) from a line to
another line
• Unstructured Languages: early BASIC, COBOL
The following is a piece of simple COBOL code,to
show the features of unstructured programming

000100 IDENTIFICATION DIVISION.


000200 PROGRAM-ID. HAPPYNEWYEAR.
000300
100000 PROCEDURE DIVISION.
100100
100200 MAIN-LOGIC SECTION.
100300 BEGIN.
100400 DISPLAY " " LINE 1 POSITION 1 ERASE EOS.
100500 DISPLAY "Happy New Year!" LINE 15 POSITION 10
100600 STOP RUN.
100700 MAIN-LOGIC-EXIT.
100800 EXIT.
• Unstructured programming introduces: iteration,
branch and GOTO
• Unstructured programming model does not have
the procedure concept, but the primitive
subroutines are allowed
• Here, the subroutine possibly has several
entrance points and the exit points.
• The program control may go into or exit from this
subroutine directly in any point
• This is not allowed in structured programming.
非结构化编程的样式
000100 statement 1
000200 statement 2
程序执行顺序: 按照顺序执行程
100200 statement 3, GO TO 100500 序,遇go to x语句,跳转到x行
100300 statement 4
100500 statement 523, call Subroutine 1
可以在一个语句中
100600
调用某个子程序
100700 statement 800
100800
100000 PROCEDURE DIVISION.
100100 Subroutine 1 {…}
Subroutine 2 {…} 子程序甚至没有参数传递,可
Subroutine 3 {…} 能有几个入口和出口。仅仅是
为了反复调用一段程序提供方
Subroutine 4 {…} 便。
Subroutine 5 {…}
• Disadvantages of Unstructured programming:
a) It is difficult to follow program logic.
b) It is hard to incorporate other code;
c) It is not easy to modify code (都是goto惹的祸)
d) It is difficult to test particular portions of the
code
• Structured programming is a programming
paradigm aimed on improving the clarity, quality,
and development time of a computer program by
making extensive use of
– 子程序:subroutines,
– 块状结构:block structures and
– 循环结构:for and while loops.
• 结构化编程抛弃了GOTO语句。
• Language that support structured
programming: started from ALGOL68, C
• 结构化程序定理:只要一种编程语言可以依三个
方式组合其子程序及调整控制流程,则每个可计
算函数都可以用此种编程语言来表示(实现任何
算法)。三个调整控制流程的方式为:
u序列结构:按照顺序执行一个子程序,然后再
执行另一个子程序
u选择结构:根据布尔表达式的值,执行两个子
程序中的一个子程序(if, else if, else);
u迭代结构(for, while):执行子程序,直到一个
布尔表达式为true
Control
Statement Control
No Yes
No
Yes
Statement Statement Statement
Statement

Statement

序列结构 选择结构 循环结构


• 该定理强调使用子程序、块状结构和for和
while循环;而不是使用简单测试后再使用
跳跃语句,例如goto语句;
• 该定理保证了只要一种编程语言支持序列
结构、选择结构、循环结构(而不必使用
goto语句语句),则可以实现任何可计算函
数;
• 该定理是结构化编程的理论基础。
Call and Return Architecture
• Call and return architecture has been of a
great influence for the past 30 years
• The Main Program and Subroutine
architecture and OO System in this lecture
are sub types of the call and return
architecture
• A system designed in call and return
architecture uses divide and conquer
strategy.

• Its main idea is to divide the whole system


into some smaller blocks to reduce the
complexity and enhance the modifiability

• The execution order of the Call and return


system is usually controlled by a single
thread
M After calling a subroutine,
1 control is returned to the
10 calling sunroutine
3 8
2 9
A B E
4 7

5 6
A software component
C D can be executed only if
it gets the control

The control flow of call and return architecture


是一种Call and return 架构
代表结构化编程
• Architecture: the system is composed of a main
program and some hierarchically organized
subroutines
– Main program call higher level subroutines
– Higher level subroutines call lower level
subroutines
– The correctness of a subroutine often depends
on the subroutine it calls

【注】A subroutine or subprogram (also called procedure,


method, function, or routine) is a portion of code within a
larger program, which performs a specific task and is
relatively independent of the remaining code.
main

task1 task2 High level


task

subtask11 subtask12 subtask13 subtask21 subtask22 Lower level


task

Lowest level
subtask121 subtask122 task
main

An arrow means
a function call
Steps in structured design:
• STEP 1: Draw Data Flow Diagram: Represent the
problem as the flow of data through a system.
• STEP 2: Draw Structure Chart: Represent the
program as a hierarchy of functional components.
This is derived from the data flow diagram.
• STEP 3: Evaluate the Design
• STEP 4: Prepare the Design for Implementation
Divide logical design into physical implementation
units.
Example: a medicine cost computation problem
• Requirement specifications:
• Medicine Cost Computation program inputs
medicine name, and the program will return the
cost per unit amount of the given medicine
• The medicine cost include two part
Ø Research cost, and
Ø Production cost
Medicine cost computation DFD: layer 1
Medicine Medicine Cost Medicine
name Computation cost

Medicine cost computation DFD: layer 2


Calculate
Medicine Enter Output Medicine
name medicine
medicine name cost cost
cost

Medicine cost computation DFD: layer 3

Medicine Enter
Get research Get production Output Medicine
name medicine Cost per unit Cost per unit cost cost
name
Layer 3 DFD diagram can be translated into the program
structure chart below
Medicine Cost
Computation

Total
Total medicine
medicine
cost per cost
unit
Enter medicine Calculate medicine Output cost
name cost

Medicine
production
cost

Get research Get production


Cost per unit Cost per unit
Problems with top-down functional design

1. The functional viewpoint is difficult to


evolve
2. Real systems are hard to characterize
functionally
3. The functional focus loses sight of the data
4. Functional orientation produces less
reusable code
1)The functional viewpoint is difficult to
evolve
– The top-down approach creates a good software
model for the initial requirements of a system.
– But as that system changes and new
requirements are added, the functional
architecture becomes more and more unwieldy
• Because the software is designed as tree
structure, changes usually require extensive
pruning and grafting
• Maintenance becomes more and more difficult
Need to add
function here A program is composed of 58 functions
Pruning/
grafting
2)Real systems are hard to characterize
functionally
– Most large systems do not have a top, e.g., a
database system involving tools for querying data,
changing data, and keeping data consistent.
– If there is no one function central to these diverse
concerns, then define these systems based on a
single top-level function is artificial and yields
overly complex and non-adaptive architectures.
3)The functional focus loses sight of the data
– The top-down design does not capture anything
about the data involved in the program.
– Usually, the same data is shared among a number
of functions (for example, updating, deleting,
inserting and querying a database table).
– Since the decomposition only highlights the
functional aspects of the problem, the influence of
the data structures on the problem is lost
4)Functional orientation produces less
reusable code
– Top-down design works by continually refining a
problem into simpler and simpler chunks.
– Each chunk is analyzed and specified by itself,
without much regard for the rest of the system
– However, each program element is designed with
only a limited set of requirements in mind.
– Since it is unlikely that this exact set of
requirements will appear in the next problem, the
program's design and code is not general and
reusable.
是一种Call and return 架构
面向对象设计产生类图
What is an Object?
• floats, ints, chars: primitive “objects” in C++
(and in C).
• OOD/OOP extends this idea to “higher-level”
objects.
• The basic concept here is that objects serve to
unify the ideas of
– algorithmic abstraction,and
– data abstraction

Tiger
-sex: String Data
-age: int Abstraction
-species: String
+eat(): void
+hunt(): void Algorithm
+run(): void Abstraction
+sleep(): void
1)
– Restrict access to certain information
• private variables; code inside a method
2)
– Share one definition of shared functionality

3)
– Determine actual operation to call at runtime
– Don’t know which object to invoke before the program
runs, in the run-time, will dynamically decide which
object to use.
4)
– Exploit capsulation and locality
Advantages of OOD
Advantages of OOD

c) Real world mapping


For some systems, there may be an obvious
mapping from real world entities to system objects
Easy decomposition of a system
the bundling of a set of accessing routines with
the data they manipulate allows designers to
decompose problems into collections of interacting
agents.
Inheritance introduces complexity and this is
undesirable, especially in critical systems

ontrol system in Boeing 747:


Ø 5 years,
Ø $5 billion,
Ø 500 software developers
Difference Between Structured design and OO
Design
• Structured design focuses on the decomposition of
software into various functional components. i.e.,
program is organized into a collection of functions,
which will be executed in a defined order to produce the
desired result.
• OO design focuses on the organization of software into
a collection of components, called objects, that group
together
– Related items of data (properties)
– Operations that are to be performed on the data
(methods)
.
The sun is rising in the east
Flowers are blooming
The sun is rising in the east
sun is rising in the east the
is rising in the east the sun
rising in the east the sun is
in the east the sun is rising
the east the sun is rising in
east the sun is rising in the
Flowers are blooming
are blooming Flowers
blooming Flowers are
are blooming Flowers
blooming Flowers are
east the sun is rising in the
flowers are blooming
in the east the sun is rising
is rising in the east the sun
rising in the east the sun is
sun is rising in the east the
the east the sun is rising in
The sun is rising in the east
Function
calls

Memory
access

Main program and subroutine Design of the KWIC Program


• The current KWIC system represents its data in
the following format:
• Characters from the input file are stored in a
character array named chars_. Words are
delimited by a single space character.

Data Representation
• line_index_ is an integer array, which keeps
indices of characters from the character array.
Each index kept in the line index array is the
index of the first character of a particular line.
• Two dimensional integer array (matrix) named
circular_shifts_ represents the set of all circular
shifts of all original lines.
• A particular circular shift is represented as a pair
of indices.
– The first value in such a pair is an index of the
original line from the line index array.
in the pair is an index of a
character from the character array.
• The character pointed by this index is the first
character of a particular circular shift.
Two dimensional integer array (matrix) named
alphabetized_ represents the sorted lines. This
array has the same format as the circular shifts
array. The difference is that in the alphabetized
array lines come in a different order, i.e., they are
sorted alphabetically.
• Processing Algorithm
• The main function controls the execution of the KWIC
program:
• The input function is called to read and parse the lines from
an input file. This function reads and processes all lines at
once and represents it by means of the character (chars_)
and line index (line_index_) array, as described before.
• The main function calls the circularShift function, which
produces circular shifts of each particular line and stores it
in the circular shifts array (circular_shifts_), as discussed
before.
• After the circular shifts have been produced, the main
function calls the sort function, which sorts circular shifts
alphabetically. The result is stored in the alphabetized array
(alphabetized_), as described before.
• Finally, the main function calls the output function, which
prints the sorted lines.
The solution with OO architectural
style decomposes the system into six modules:
module, responsible for holding all
characters from all words and lines.
module, responsible for reading the data
from a file and storing it in LineStorage module.
module, responsible for
producing circular shifts of lines stored in
LineStorage module.
module, responsible for sorting
circular shifts alphabetically.
module, responsible for prinitng the
sorted shifts.
module, responsible for
controling the sequence of method invokations in
other modules.
• Contrary to the main/subroutine solution, in
the object-oriented solution the data is
between the computational
components.
• Instead, each module provides an
that permits other components to access data
only by invoking methods in that interface.
Main program
Java class
Each module from the architectural design maps
exactly onto one class:
• KWIC class (Master Control module),
• Input class,
• Output class,
• LineStorage class,
• CicrularShifter class and
• Alphabetizer class.
The method in the KWIC class

execute(String file) {

Input input = new Input();


Output output = new Output();

input.parse(file, lines);
shifter.setup(lines);
alphabetizer.alpha(shifter);
output.print(alphabetizer);
}
lines
file

lines input.parse(file, lines);

shifter.setup(lines);
alphabetizer.alpha(shifter);
alphabetizer

output.print(alphabetizer); Screen

Are red flowers


Flowers are red
Red flowers are
– The parse method reads the data from the file. For each
line in that file, it creates a new line in the LineStorage by
invoking its addEmptyLine method. To add words to the
new line Input object invokes addWord method on
LineStorage. The iterative nature of this process is
symbolized in the diagram with * sign in the front of the
addWord method name.
At the next step the KWIC object invokes the alpha
method

of Alphabetizer instance. This method takes as an


argument the CircularShifter object. It then sorts
shifts alphabetically, retrieving each of them from
CircularShifter object by invoking its
getLineAsString method. The sorted lines are
written into sorted_[];
• Finally, the KWIC object invokes the print
method on Output instance. This method takes
as an argument the Alphabetizer object from the
previous step.
• It iterates then through all lines from the
Alphabetizer object by invoking getLineAsString
method.
Professor:
Yushan (Michael) Sun
Fall 2016
2. Class Relations
Data have been encapsulated(封装)

Functions are provided


A lovely young
lady

An instantiation of the Person class


Return
Another instantiation of the Person class
Class Relations (类间关系)
• Association relation (关联关系)
• An association between two classes represents
a collaboration between the classes or their
corresponding instances. Association relation
includes:
– Aggregation relation(聚合关系)
类B以一个实例化对象的
形式作为A的一个属性

– Dependency relation(依赖关系)
表现为类B作为参数被类A某个方法使用
Class Relations

Employee String
-name: String

Driver drives Car


-car: Car

In Java language, association relation can be realized


by instance variables.
Class Relations

(聚合关系) is one kind of


association relationship. It is a stronger type of
association.
ØThis relation expresses a relationship of a
whole and a part.
ØAn aggregation has a hallow diamond end
pointing to the part containing the whole.
Class Relations

Car 1 1 Engine
-engine: Engine
-wheels: Wheels 1 4
-parts: Parts Wheels

1 *
Parts

Aggregation relation
Class Relations

• 关联关系与聚合关系的区别:
• Like association, aggregation is realized by
instance variables. But the difference is that:
, the classes
being associated are in the same one level
, the classes
being associated are in different levels, one
represents the whole and the other represents
the part
Class Relations

• Dependency relation (依赖关系)


• Dependency relation is a relation in which one
class is dependent on another class.
– One person can buy a car and house and so
Person class is dependent on Car and House
classes.
– Use dotted lines to represent dependency
relation
Class Relations
通过参数,
达到关联

Person Car

buy(Car car): void House


buy(House house): void

• Different from association, Person class has no attributes of


class Car and House.
• The object of Car and House is passed into class Person by
using parameter in buy(Car car) and buy(House house)

Return
SortStrategy

US cars
USCar
+run()
+break()
+accelerate
+stop()
+getInstructions()

+run() +run() +run()


+break() +break() +break()
+accelerate +accelerate +accelerate
+stop() +stop() +stop()

US cars
getInstructions()
2) use an abstract class by inheriting it
– Can be used by other classes to create objects
– Can be inherited by its subclasses

– Can not be used by other classes to create


objects
– Can be inherited by its subclasses
Different implementations of method climbTree
Three different kinds of animals climb tree
in three different ways
Form of a Class Hierarchy
Form of a Class Hierarchy

Return
Java Interface( )

}
Java Interface( )

Properties of Java interface:


• A Java interface
– Has no constructor ( )
– One Java interface can have many very
different implementations
– A Java class can implement as many Java
interfaces as one wants
Java Interface( )

+deposit()
+withdraw()
+transfer()

+deposit() +deposit() +deposit()


+withdraw() +withdraw() +withdraw()
+transfer() +transfer() +transfer()

One Java interface can have many very different implementations


Java Interface( )

A Java class can implement as many Java


interfaces as one wants
Java Interface( )

, an interface can
define a set of related functions for some special
use
Java Interface( )

Code for dynamic binding:

Account act
if(usrChoice == 1)
act = new
if(usrChoice == 2)
act = new Savings
if(usrChoice == 3)
act = new Online
Java Interface( )
: from Java API

Public interface Runnable{


Public abstract void run( )
}
public interface Runnable. The Runnable interface
should be implemented by any class whose instances
are intended to be executed by a thread. This interface is
designed to provide a common protocol for objects that
wish to execute code while they are active.
For example, Runnable is implemented by class Thread.

Return
Design Principles
1) Interface segregation principle
Ø To avoid Interface contamination
2) Open-closed principle
Ø Open for extension
Ø Closed for modification
3) Dependency inversion Principle
Ø In traditional procedural system design, higher level
depends on Lower level
Ø In OO design,

Program to an interface, not an implementation


• Abstraction should not depend upon details.
Details should depend upon Abstractions
1. Interface segregation principle

Example of interface
contamination -companyName: String
-companyAddr: String
-trade:
-amount: double
-taxRate: double
-trade: Trade -employeeName: String
-employeeNum: String
-salary: double

This class contains 12


methods, some of them
are unrelated, which
means that this is an
contaminated interface
1. Interface segregation principle

- c o m p a n y :
Company +computeTax(): void

According to functionalities, separate the original interface into


several classes, i.e., follows the Interface segregation principle
2. Open/closed principle

• Open/closed principle (开闭原则)


• Open for extension, and closed for
modification
• 在面向对象编程中,开/闭原则声称“软件
实体(类)应该对扩展开放,但是对修改
关闭”,也就是说这样一个实体可以允许
其行为被扩展或修改而不改变它的源代码。
3. Dependency inversion principle

Dependence
direction

In traditional procedural system design, higher level


depends on Lower level
Dependency inversion principle

Dependence
direction

In OO-design:
1)Abstraction should not depend upon details. Details
should depend upon Abstractions
2)Program to an interface, not an implementation
Return
Software Architecture

Lecture 2. Dataflow Systems

Professor:
Yushan (Michael) Sun
Fall 2016
Lecture 2. Dataflow Systems
In general, data can flow
in arbitary patterns
When data arrive, the component is
activated. It does nothing when there are
no data
We are interested in
nearly linear data flow
system

Or in very simple, highly


constrained cyclic
structures
General architecture of dataflow architecture
We pay attention to the locus of control flow that
moves through the program
• Data may accompany the control but is
not dominant
• The order of execution of the program is
concerned
• Main concern is how data moves through a
collection of (atomic) computations
– As data moves, control is activated
– Reasoning is about
• data availability,
• transformation and
• latency
n Decompose system into
modules
− Abstraction isolates complexity
− Operations performed on data objects
n Compose modules into a graph
− Connect modules forming directed graph
− Interfaces are negotiated to match data
types
n Run the graph
− Data flows between the modules
− scheduler automates parallelism
− memory manager optimizes memory
usage
1960年代-1970年代数据处理的例子

Ibm1401 大型机。数 大型机,IBM 1960制


造, 28MB硬盘用于
据处理,1959年生产
航天领域;1962生产
a) Batch sequential process is formed by a sequence of
processing steps, intermediating by some kind of
storage, such as megatapes, hard disk, etc.
b) Each step will do some operation on the input storage
to get some useful information or modify the contents
of the source storage and then save the resultant data
to its sink storage.

Proc 1 Proc 2 Proc 3


a) Processing steps are independent
programs (no interaction between any
two processing steps)

Proc 1 Proc 2 Proc 3

Proc1,Proc2和Proc3互不调用
b) Each step run to completion before the
next step starts
• Proc1完整地处理完D1中的数据将数据存入D2
• Proc2完整地处理完D2中的数据将数据存入D3
• Proc3完整地处理完D3中的数据将数据存入D4
c) Data is transmitted as a whole between
steps
:
– classical data processing
Online
Data Edit Sort
entry
Application
input Reject
report
Computer
output
Print

Update1 Update2

Old New Old New


Master1 Master1 Master2 Master2
Sun, Mike 356821 TV 888.56 324-56-7348
Lee, Mary 842674 radio 65.44 563-27-8977
Juell, Paul 257215 Telephone 97.05 678-23-1567
Microwave
Nygard, Ken 573245 56.88 974-67-8577
oven
Magel, Ken 834265 refrigerator 988 874-26-7847
Hunt, Paul 332184 Bicycle 523 223-56-6878
Eric, Vosika 257652 jewellery 1005 564-31-0976

Ejected data, wrong format


Liu, Elle 672452 356 346-12-6788 camera
Eric, Vosika 257652 jewellery 1005 564310976
Hunt, Paul 332184 Bicycle 523 223566878
Juell, Paul 257215 Telephone 97.05 678231567
Lee, Mary 842674 radio 65.44 563278977
Magel, Ken 834265 refrigerator 988 874267847
Microwave
Nygard, Ken 573245 56.88 974678577
oven
Sun, Mike 356821 TV 888.56 324567348
4.
5.
Validate Sort Update Report

Batch Sequential Database Architecture


Year 2000 problem and political issues.
In a text file, change all year expressions “xx” into
“xxxx”, e.g. “89” into “1989”, and change all
expressions “Republic of China” into “Taiwan”

legacy.txt

new.txt
Original txt file:
Television $3800 Japan 95-12-11
Television $3600 Germany 88-12-01
Microwave $3800 Japan 95-12-11
Microwave $3600 Germany 88-12-01
Television $3800 Republic of China 95-12-11
Television $3300 Germany 89-02-01
Microwave $3800 Republic of China 95-12-11
Microwave $3300 Germany 89-02-01
Washing Machine $3800 Japan 95-12-11
Washing Machine $3600 Germany 88-12-01
Television $3800 Republic of China 95-12-11
Television $3300 Germany 89-02-01
Washing Machine $3800 Republic of China 95-12-11
Washing Machine $3300 Germany 89-02-01
After Y2K (in Tape 3):
Television $3800 Japan 1995-12-11
Television $3600 Germany 1988-12-01
Microwave $3800 Japan 1995-12-11
Microwave $3600 Germany 1988-12-01
Television $3800 Republic of China 1995-12-11
Television $3300 Germany 1989-02-01
Microwave $3800 Republic of China 1995-12-11
Microwave $3300 Germany 1989-02-01
Washing Machine $3800 Japan 1995-12-11
Washing Machine $3600 Germany 1988-12-01
Television $3800 Republic of China 1995-12-11
Television $3300 Germany 1989-02-01
Washing Machine $3800 Republic of China 1995-12-11
Washing Machine $3300 Germany 1989-02-01
After Political Issue (in Tape 4) :
Television $3800 Japan 1995-12-11
Television $3600 Germany 1988-12-01
Microwave $3800 Japan 1995-12-11
Microwave $3600 Germany 1988-12-01
Television $3800 1995-12-11
Television $3300 Germany 1989-02-01
Microwave $3800 1995-12-11
Microwave $3300 Germany 1989-02-01
Washing Machine $3800 Japan 1995-12-11
Washing Machine $3600 Germany 1988-12-01
Television $3800 1995-12-11
Television $3300 Germany 1989-02-01
Washing Machine $3800 1995-12-11
Washing Machine $3300 Germany 1989-02-01
• Batch sequential faces technology
pressure : online access
:
• queries are relatively easier
• Real-time transactions
– Online updates require a shift from pure
batch to interactive processing
纯净水生产流程图
Processing
step
Data
stream
3. Pipes and Filters architecture

Process data

transmit data
3. Pipes and Filters architecture
3. Pipes and Filters architecture

Functionalities of a Pipe:
move data from a filter’s output to a filter’s
input
– One way flow
– Pipes form data transmission graph
3. Pipes and Filters architecture

– Run pipes and filters until no more


computations are possible
– Action is mediated by data delivery
3. Pipes and Filters architecture
Year 2000 problem and political issues.
In a text file, change all year expressions “xx”
into “xxxx”, e.g. “89” into “1989”, and change all
expressions “Republic of China” into “Taiwan”

legacy.txt

new.txt
3. Pipes and Filters architecture

legacy.txt

new.txt
After Input: Television $3800 Republic of China 95-12-11
After Y2K: Television $3800 Republic of China 1995-12-11
After Political Issue: Television $3800 Taiwan 1995-12-11
After Output: Television $3800 China 1995-12-11

数据以数据流的方式从左端流入,流经各个过滤器,对数据进
行处理;对于处理完的数据,立即写入到下游管道
3. Pipes and Filters architecture

:
A typical architecture of a compiler example
is pipes and filter’s architecture describing
in the next page.
3. Pipes and Filters architecture

进行语法分析

进行语义分析

生成字节码

Virtual machine
3. Pipes and Filters architecture

– Misspellings: such as “String” into “Sting”, “Super”,


“supper”
语法分析
– Omission, wrong order of tokens
语义分析
– Incompatible types: e.g., “float”, “double”

– C/C++ compiler: from source code to assembly code


– Java compiler: from Java code to bytecode。
– Java跨平台其实就是基于相同的bytecode规范做不同平台的虚拟机,我们的Java
程序编译成bytecode后就可以在不同平台跑了。
3. Pipes and Filters architecture

• Pipes and filters architecture with branches


• The pipes-and-filters pattern allows filters with
multiple input and/or multiple output pipes to be
connected in any directed graph structure.
• Such dataflow systems are difficult to design
• However, if we restrict ourselves to directed
acyclic graph structures, the problem is
considerably simplified (无循环的结构).
• In the UNIX system, the tee filter provides a
mechanism to split a stream into two streams
3. Pipes and Filters architecture

Example 5: Tee & Join in Unix


Task: Print a sorted list of words that occur more than
once
1) mknod pipeA p
2) mknod pipeB p
3) sort pipeA > pipeB &
4) cat file1 | tee pipeA | sort -u | comm -13 - pipeB > file2
3. Pipes and Filters architecture

分叉 合并
3. Pipes and Filters architecture

Example 6. 如下的Unix命令组成一个管道/过
滤器程序,将in.txt文件的包含“Heroin”的行

行排序,然后将结果输出到out.txt文件中。

cat in.txt | grep “Heroin” | sort > out.txt


3. Pipes and Filters architecture

以上命令行的管道/过滤器结构图如下。
in.txt

Cat

Grep Sort
Grep负责在文件in.txt中搜索包含 将上游管道来的
表达式“cocaine”的所有的行,
out.txt
行进行排序,以后
并且将它们输出到下游管道。 写到out.txt中
3. Pipes and Filters architecture
3. Pipes and Filters architecture

• Similarity: independent processing modules


In both Batch sequential and pipes and filters
architectures, the processing steps are
independent of each other, that is
Øone filter in pipes and filters architecture
doesn’t call any other filters in the system
Øone processing step in batch sequential
architecture doesn’t call any other processing
step in the system
Ø处理过程之间互不调用
3. Pipes and Filters architecture

ach step
runs to completion before the next step starts,
that is, data is transmitted as a whole between
steps

Incrementally transform some of the source


data into sink data, that is, the filters do stream
to stream transformation
3. Pipes and Filters architecture
3. Pipes and Filters architecture

Digital Image Processing


• Image processing problem
• Question: if you are required to do some image
processing to digital pictures (images), and you
are given two choices, batch sequential and
pipes and filters, which one should you select?
• Processing steps:
– Sharpen
– FindEdges
– HighlightEdges
– ProduceReport
3. Pipes and Filters architecture

Picture before and after image sharpening


Example Pipe-and-Filter System: Khors–An Image-
Processing Workbench
3. Pipes and Filters architecture

Image Processing Workbench (IPW)


• IPW is a UNIX-based image processing system.
• IPW includes several UNIX filter programs which
can be pipe-lined together to form complex and
powerful image processing algorithms.
• IPW includes a development environment for
creating new IPW shell scripts and programs in C.
• IPW often provides the simplest, most powerful
and efficient methods for manipulating a wide
variety of remote sensing and image data (why?).
3. Pipes and Filters architecture

• 例7 使用批处理体系结构。设计考虑设计一
个图像处理软件。该软件应该有一个用户
图形界面。该软件包含一些可以随时添加
的过滤器(filters),例如,图像模糊
(Blurring),图像锐化(Sharpening),图像变
亮(Brightening),发现图像边界
(EdgeDetector),每个过滤器完成一项特定
的图像处理功能。一些过滤器被串联在一
起,以便完成一些比较复杂的功能。我们
该系统,如图6.25。
3. Pipes and Filters architecture

img.jpg

EdgeDe
Blur Sharpen Brighten
tect

newImg.jpg

顺序批处理体系结构的数字图像处理系统对象逻辑图
3. Pipes and Filters architecture

顺序批处理软件用户界面图
3. Pipes and Filters architecture

• 例8 使用管道-过滤器体系结构设计的数字图像处理
系统。设计一个管道-过滤器体系结构的数字图像
处理系统。其功能包括用户图形界面,RGBFilter,
ThreshHoldFilter,TransFilter,GrayOutFilter分别实
现对彩色图像的三色素滤波,阈值滤波、变换滤波
与变灰滤波。

img.jpg newImg.jpg

RGBFilter ThreshHoldFilter TransFilter GrayOutFilter

设计逻辑
3. Pipes and Filters architecture

其中,RGBFilter、ThreshHoldFilter、
TransFilter、GrayOutFilter对象利用Pipe对象
从上游数据流读入数据,进行各种滤波,
并且适时地将所产生的数据写到下游数据
流中,设计类图如图6.49所示。
3. Pipes and Filters architecture

利用管道-过滤器架构设计的数字图像处理系统用户界面图
4. Process-control Paradigms
-a particular kind of dataflow
Architecture
4. Process-control Paradigms

Room heater logic


4. Process-control Paradigms

阀门 加热器
Set
point:
25 oC
4. Process-control Paradigms

software
software
4. Process-control Paradigms
4. Process-control Paradigms

Example of Beer production lines


4. Process-control Paradigms

Values of Properties of the process


that can be measured (e.g.,
Process variable whose value the
system is intended to control. (e.g.,
Process variable that measures an input to
the process. (e.g.,
. Process variable whose value can
be changed by the controller.
4. Process-control Paradigms

• Kinds of control system


4. Process-control Paradigms

No control at all, air is heated up continuously


4. Process-control Paradigms
4. Process-control Paradigms
4. Process-control Paradigms

The controlled variable is measured, and the


result is used to manipulate one or more of
the process variables. The p
4. Process-control Paradigms
4. Process-control Paradigms

Feedback control system.


A system used to adjust the process according to
measurements of the controlled variable.
The important components of a feedback controller are
– 过程定义。the process definition,
– 过程变量。the process variables (e.g. input and
controlled variables), a sensor to obtain the controlled
variable from the physical output
– 设定点。the set point (target value for the controlled
variable), and
– 控制算法。a control algorithm.
4. Process-control Paradigms

An architectural style for software that controls


continuous processes can be based on the process
control model. It contains:
1. : separate the process of
interest from the control policy.
• ,


4. Process-control Paradigms
4. Process-control Paradigms

2. Data elements: continuously updated process


variables and sensors that collect them.
• Process variables, including
• input,
• controlled, and
• manipulated variables, and
knowledge of which can be sensed.
• Set point, for controlled variable.
• Sensors, to obtain values of process variables
pertinent to control.
4. Process-control Paradigms

3. establishes the
that the control algorithm exercises.
Lecture 2

Professor:
Yushan (Michael) Sun
Fall 2016

1
Contents of this lecture

1. Introduction of the factory method


pattern

2
3
Introduction to Factory Method Pattern

• If an application object knows the exact


method it needs, it can directly instantiate the
class from the class hierarchy that contains
the method.
• See example below.

4
Introduction to Factory Method Pattern

Client
obCar: Car
Main() Car
+buyCar()
+buyParts()

-model -model -model


+buyCar() +buyCar() +buyCar()
+buyParts() +buyParts() +buyParts()

5
Introduction to Factory Method Pattern

6
Introduction to Factory Method Pattern

The choice may depend on:


– 运行状态. The state of the running application
(input from users)
– 应用配置设置. Application configuration
settings
• In such cases, an application object needs to
use conditional statements to instantiate an
appropriate class from the hierarchy to access
its services
7
Introduction to Factory Method Pattern

Client Car
obCar: Car +buyCar()
Main() +buyParts()

obCar Lincoln(m);

obCar -model -model -model


+buyCar() +buyCar() +buyCar()
obCar
+buyParts() +buyParts() +buyParts()
obCar

8
Introduction to Factory Method Pattern

该设计的缺点:
This type of design has the following disadvantages:
.
Because every application object that intends to
use the services offered by the class hierarchy
needs to implement the class selection criteria, it
results in a between an
application object and the service provider class
hierarchy.

9
Introduction to Factory Method Pattern

.
Because class selection criteria needs to take
all the factors that could affect the selection
process into account, the implementation of an
application object could contain inelegant
conditional statements.

.
It requires an application object to be fully
aware of the existence and the functionality
offered by each class in the service provider
class hierarchy.
10
Introduction to Factory Method Pattern

• 怎样改善以上设计?
• In such cases, use the Factory Method Pattern,
which recommends
– encapsulating the functionality required to
select and instantiate an appropriate class
inside a designated method called a factory

11
Introduction to Factory Method Pattern
Client
obCar Car
main() Car

工厂类 +buyCar()
+buyParts()
CarObjCreator
工厂 obCar Car
方法
-model -model -model
If (usrChoice==1)
obCar =new Lincoln(m); +buyCar() +buyCar() +buyCar()
else if (usrChoice==2) +buyParts() +buyParts() +buyParts()
obCar =new Cadillac(m)
else if (usrChoice==3)
obCar = new Buick(m)
return obCar;
12
Introduction to Factory Method Pattern

• Thus, a factory method can be defined as a method


in a class that:
Selects an appropriate class from
a class hierarchy based on the application
context and other influencing factors
Instantiates the selected class
and
returns it as an
instance of the parent class type
13
Introduction to Factory Method Pattern

Application objects can make use of the factory


method to get access to the appropriate class
instance. This eliminates the need for an
application object to deal with the varying class
selection criteria.

14
Introduction to Factory Method Pattern

.
(隐藏初始对象的细节)
The factory method also implements any
special mechanisms required to instantiate the
selected class.
– This is possible

. The factory method hides these details from


application objects and eliminates the need for them
to deal with these intricacies.

15
Introduction to Factory Method Pattern

Because the factory method returns the selected


class instance as an object of the parent class
type, a client program does not have to be
aware of the existence of the classes in the
hierarchy.

16
以下给出两种不同的工厂方法模式
–简单工厂方法模式
–工厂方法模式

17
18
Diagram of Simple factory pattern, 19
• 包含业务逻辑. Contains business logic that
application needs
• 创建产品类对象. Factory method creates an
object of Product type when called by the
client program, and return this object to the
caller object

20
• Java interface or abstract java class
• Common interface or super class for the
concrete subclsses

• Concrete Java classes to implement interface


Product or to extend abstract class Product

21
可以传递参
数给工厂类
Creator.factory(p)

仅仅负责创建对象

Simple Factory Pattern Implementation


22
Example of Auto Insurance Policies
汽车保险的例子-简单工厂方法模式

• The following class diagram represents a


design using factory method pattern to
query about the features of different types
of auto insurances.

23
24
使用简单工厂方法模式设计的汽车保险类
interface to claim various
insurance policies (here d

AutoInsurance
25
is a factory class with a
factory method:
getPolicyObj(String option)
which will create and return an object of
AutoInsurance type.
• Actually, it will create and return an object of
one of the implementing class according to
the chosen parameter “opt” entered.

26
public interface AutoInsurance {
abstract String describe();
}

27
public class Body implements AutoInsurance{
private String description;

public String describe(){


description = " Body Injur Liability”;
return description;
}
}

28
public class Collision implements
AutoInsurance {
private String description;

public String describe() {


description = "Collision Coverage”;
return description;
}
}
29
public class Com implements AutoInsurance{
private String description;

public String describe() {


description = "Comprehensive Coverage”;
return description;
}
}
30
public class Person implements AutoInsurance
{
private String description;

public String describe() {


description = "Personal Injury Protection”;
return description;
}
}

31
public class PolicyProducer{
public static AutoInsurance getPolicyObj(String opt){
AutoInsurance policy = null;
if(opt.compareTo("bodyInjure") == 0){ 根据参
policy = new Body(); 数不同
} 创建不
else if(opt.compareTo("collision") == 0){ 同对象
policy = new Collision();
}
else if(opt.compareTo("com") == 0){
policy = new Com();
}
else if(opt.compareTo("personInjure") == 0){
policy = new Person();
}
return policy; // 以超类的类型返回
}} 32
用户图形界面的监听器代码
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(SHOW)) {
String type = (String) getSelectedItem();
String option="";

if (type.equals(BODYINJURE)) {
option=“bodyInjure";
} 创建对象的
else if (type.equals(COLLISION)) {
option="collision"; 责任就交给
} 大哥你了。

AutoInsurance ai = PolicyProducer.getPolicyObj(option);
String desc = ai.describe();
txtForInfo.setText(desc);
}
33
}
.
The factory class contains necessary logic,
which can decide which instances of the
product class to create and when to create
.
The client class doesn’t have to create object of
the product classes. It will just act as consumer.
(责任分离)
The simple factory pattern have realized the
responsibility separation.
34
Client class is independent of the creation of
the object.

35
.
– The factory class must know every product.
It must know how to create object of the
newly added sub classes and when to
provide them to the client.
– Thus, adding new sub classes in the Product
class hierarchy will need to modify the
source code of the factory class

36
37
+factory: Product +Operation()

+factory: Product +factory: Product +Operation: +Operation:

<<create>>

<<create>>
38
Example of Auto Insurance Policies
汽车保险的例子

• The following class diagram represents a


design in factory method pattern to query
about the features of different types of
auto insurances.

39
工厂方法模式-汽车保险的例子

+describe()

+describe()

+describe()

+describe()
interface to claim various
insurance policies (here d

AutoInsurance
41
Example of Auto Insurance Policies
汽车保险的例子

• 接口类 PolicyProducer.

42
Example of Auto Insurance Policies
汽车保险的例子

public interface AutoInsurance {


abstract String describe();
}

43
Example of Auto Insurance Policies
汽车保险的例子

public class Body implements


AutoInsurance {
private String description;

public String describe() {


description = “ Body Injur Liability:“;
return description;
}
}
44
Example of Auto Insurance Policies
汽车保险的例子

public class Collision implements


AutoInsurance {
private String description;

public String describe() {


description = “Collision Coverage: ”;
return description;
}
}

45
Example of Auto Insurance Policies
汽车保险的例子

public class Com implements AutoInsurance {


private String description;

public String describe(){


description = “Comp Coverage:”;
return description;
}
}
46
Example of Auto Insurance Policies
汽车保险的例子

public class Person implements AutoInsurance


{
private String description;

public String describe(){


description = "Personal Injury “;
return description;
}
}
47
Example of Auto Insurance Policies
汽车保险的例子

public interface PolicyProducer {


public AutoInsurance getPolicyObj();
}

public class BodyFactory


implements PolicyProducer { 工厂方
public AutoInsurance getPolicyObj() { 法无条
return new Body(); 件语句
}
}

48
Example of Auto Insurance Policies
汽车保险的例子

public class CollisionFactory


implements PolicyProducer { 工厂方
public AutoInsurance getPolicyObj(){ 法无条
件语句
return new Collision();
}
}

49
Example of Auto Insurance Policies
汽车保险的例子

public class ComFactory


implements PolicyProducer{ 工厂方
public AutoInsurance getPolicyObj() { 法无条
return new Com(); 件语句
}
}

50
Example of Auto Insurance Policies
汽车保险的例子

public class PersonFactory implements


PolicyProducer {
工厂方
public AutoInsurance getPolicyObj() { 法无条
return new Person(); 件语句
}
}

51
Example of Auto Insurance Policies
public class FactoryMethodGUI extends JFrame {
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {

if (ae.getActionCommand().equals(SHOW)) {
String t = (String) cmbInsuranceType.getSelectedItem();
PolicyProducer pp=null;

//创建工厂子类对象
if (t.equals(BODYINJURE)) { pp=new BodyFactory(); }
if (t.equals(COLLISION)) { pp=new CollisionFactory (); }
if (t.equals(PERSONINJURE)) { pp= new PersonFactory (); }
if (t.equals(COMP)) { pp= new ComFactory (); }

AutoInsurance ai = pp.getPolicyObj();
String desc = ai.describe();
}
} }} 52
53
静态工厂方法

54
+Operation(): void
+factory: Product

+Operation: +Operation:
+factory: Product +factory: Product void void

<<create>>
动态工厂方法
<<create>>

55
Øthe center of the simple factory pattern is a
concrete factory class.
ØThe center of a factory pattern is the
abstract factory class (or interface),

56
Ø In the simple factory method pattern,
the factory method is static and
Ø in the factory method pattern, the
factory methods are dynamic and are
distributed in the concrete factory classes

57
If a new product is added to the product
hierarchy, then what needed is to add a sub
concrete class to the product hierarchy and a
sub class to the factory hierarchy.
– it is not necessary to modify the abstract
factory and the existing subclasses of the
concrete factory method (工厂类的已有源
代码不需要改变)
– It is not necessary to change the client
class (假设client暂时不用该新功能),
58
+Operation():
+factory: Product void

+factory: +factory: +factory:


+Operation: +Operation: +Operation:
Product Product Product void void
void
<<create>>
<<create>>
<<create>>
59
Like the simple factory pattern, the factory
method in the concrete creator returns an
object of type Product and not an object of the
concrete product class.

60
61
何时使用工厂方法模式?
You should consider using a Factory method
pattern when
ØA class can’t anticipate which kind of class of
objects it must create (大量的条件语句).
ØA class uses its subclasses to specify which
objects it creates (此时,创建对象的任务分散
在客户类的子类中,比较乱,可以使用工厂方法
模式将创建产品类的子类对象的责任分离出来).
ØYou want to localize the knowledge of which
class gets created.
62
1. Product is an abstract class, and the pattern
must return a complete working class.

Client 2) 调用方法c.describe()
-obCar Car Car
+main() +advertise()
+describe()
1)请求创建对象c

CarObjFactory
-obCar Car Lincoln Cadillac Buick
-model: String -model: String -model: String
+createCarObj: Car
+describe() +describe() +describe()

超类Car是抽象类,因
此只能创建子类的对
象并且返回给调用者 63
2. Product class contains all default methods and is
only subclassed for cases where the default
methods are insufficient.

Client Felidae 产品类Felidae是正


2) 调用方法: f.run() +hunt() 常的具体的类;包含
obCar Car +feed() 了大部分功能;子类
main() +breed() 包含了很少的功能
+run()
1) 请求创建对象f

CarObjFactory
obCar Car Cat Lion Cheetah
-model: String -model: String -model: String
+createCar: Car +climbTree() +climbtree()
+climbTree()

不建议将产品超类写成具体类 64
3.
. In this case, the classes may share the
same method names but may do something quite different.

Client 2) 调用方法: c.describe() Car


obCar Car +describe()
main() +getPrice()

1)传递参数p,请求创建对象c

CarObjFactory Lincoln Cadillac Buick


obCar : Car -model: String -model: String -model: String
+describe() +describe() +describe()
+createCar(p: String): Car
+getPrice() +getPrice() +getPrice()

将参数p传递给工厂
类,工厂方法根据此 65
参数创建合适的类的
对象,并且以Car类
型返回给调用者
Client 3)调用方法c.getPrice()
obCar Car
main() 1)getFactory(p)获得工厂子类对象s
2)s.createCar(),获得Car子类对象c,
并且将c返回给Client对象
Car
CarFactory
+describe()
obCar : Car
+getPrice()
+getFactory(p) 静态方法
+createCar(): Car

Lincoln Cadillac
CadFactory LinFactory -model: String -model: String
obCar : Car obCar : Car +describe() +describe()
+createCar(): Car +createCar(): Car +getPrice() +getPrice()
Software Architecture

Lecture 3. Case Study on Dataflow


System

Professor:
Yushan (Michael) Sun
Fall 2015
Lecture 3. Case Study on Dataflow System

Content of the lecture:


Case study 1. Legacy File Update
Case study 3. Cruise Control
Case study 2. Instrumentation Software
问题描述:利用管道-过滤器体系结构设计一个旧文件
更新系统
In a text file,
1) Fix the Year 2000 problem: Find and change all
year expressions “xy” into “19xy”, e.g. “89”
into “1989”, and
2) Fix political issues: find and change all
expressions “Republic of China” into “Taiwan”
Design four filters:
Input, Y2K, Politics, output
Each filter processes the data and sends it
to the next filter. The four filters are connected
by three pipes.
The control is distributed.
• Each filter can run whenever it has data on which
to compute. Data sharing between filters is
strictly limited to that transmitted on pipes
Input Y2K Politics Output
使用3个管道将4个过滤器连接起来

Input Y2K Politics Output


c) Find and fix Y2k problem in this line
connected to pipe the
output stream of Y2K filter.
a) read character stream from the pipe
b) organize them into a line
c) Find and fix the political problem in this line
d) Once a line is fixed and then write it to the
pipe

connected to pipe the


output stream of .
– read character stream from
– writes them to the standard output.
manages filter and pipe
mechanism, by creating a pipeline of
the above described filters.
shared between Input filter and Y2K
filter,
– this pipe is the output pipe for Input filter and the
input pipe for Y2K filter.
shared between Y2K filter and Politics
filter,
– this pipe is the output pipe for Y2K filter and the
input pipe for Politics filter.
shared between Politics and Output
filter,
– this pipe is the output pipe for Politics filter and the
input pipe for Output filter.
从而,我们得到程序的逻辑结构如下
输入与输
出端口
Filters in the system are represented by an
abstract class named Filter. An instance of Filter
class is composed of:
, from which the filter object
reads the data
, to which the filter object
writes the processed data
– Transform(): the abstract method that
• Inputs data (in Input filter),
• Finds Y2K and processes Y2K (in Y2K filter),
• Finds and fixes political problem (in Politics filter)
• outputs data
• Pipes in the Legacy file update system are
represented as instances of the Pipe class.
• An instance of the Pipe class is a composition
of two streams: an input and an output stream.
• Pipe class connects these two streams in the
following way.
– The data that is written to the input stream is
transmitted to the output stream. In this way
these data become available for reading from
the output stream.
and

The Pipe class encapsulates the input and output streams


as its private variables and provide just a simple public
Interface for writing data to and reading data from a pipe
object.
Input Y2K Politics Output
p1 p2
cdefg

Pipe p1 = new Pipe()

p1

cdefg p1

cdefg p1
cdefg p1

Pipe p2 = new Pipe() p2

p1

经过read()以后,P1的内
容被消费了

cdefg p2

cdefg p2
• So a filter simply write some data to a pipe object by
calling its write method. These data become then
available for the next filter, which can call the read
method of the pipe object to retrieve the data.
Do something
with read in
data

Input Y2K Politics Output


: Pipe objects limit
the amount of data they can hold.
. However, whenever clients
read the data from a pipe, this data is
considered "consumed" and the space that was
occupied by the retrieved data is made free
again.
It maintains the intuitive flow of
processing.
It supports reuse, since each filter can
function in isolation
: New functions are easily added
to the system by inserting filters at the appropriate
points in the processing sequence.
: it’s easy to modify the system
since filters are logically independent of other
filters.
• Poor Interaction: It is virtually impossible to
modify the design to support an
system. For example, deleting a line would require
some persistent (持久的) shared storage, violating
basic principle of this approach.

: The solution uses space


inefficiently, since each filter must copy all of the
data to its output ports.
Case study 3. Cruise Control
Case study 3. Cruise Control
On, when the brake is pressed;
the cruise-control system temporarily
reverts to manual control if the brake is
pressed.
Increase or decrease the maintained
speed; only applicable if the cruise-control
system is on.
Resume the last maintained speed; only
applicable if the cruise-control system is
on.
Timing pulse every millisecond
output from the system, Digital value for
the engine throttle setting
Case study 3. Cruise Control

System on/off
Engine on/off
Pulses from wheel
Accelerator Throttle
Brake
节流阀,喷油阀
Increase/decrease
speed
Resume speed
Clock
Case study 3. Cruise Control

• Computational elements
• Process definition:
• the process takes a throttle setting as input and
controls the speed of the vehicle.
Case study 3. Cruise Control

: this algorithm
. gets the current speed from the
wheel pulses,
. compares it to the desired speed, and
. changes the throttle setting.
. The clock input is needed to determine
current speed from the intervals between wheel
pulses.
The policy decisions about how much
to change the throttle setting for a given
discrepancy between current speed and desired
speed is localized in the control algorithm.
Case study 3. Cruise Control

: the current speed of


the vehicle.
: the throttle setting
: the desired speed is set and
modified by
• the accelerator input and
• the increase/decrease speed input,
respectively.
Case study 3. Cruise Control
Case study 3. Cruise Control

: For cruise
control, the current state is the current speed,
which is modeled on data from a sensor that
gives wheel pulses, using the clock.
Case study 3. Cruise Control
Case study 3. Cruise Control

Active/inactive
toggle

Wheel rotation
Throttle
Engine
setting
Desired
Speed
speed
sensor

Pulses from wheel

FIGURE 3.18 Control Architecture for Cruise Control


Case study 3. Cruise Control

Inactive
fast

Accel set point


Engine on
Interactive System on
OFF nil ACTIVE

Engine off Brake Resume


System off
All states Inactive
All states slow
Except OFF

FIGURE 3.19 State Machine for Activation


Case study 3. Cruise Control

Event Effect on desired speed


Engine off, system off Set to "undefined."
System on Set to current speed as
estimated from wheel pulses.
Increase speed Increment desired speed by
constant.
Decrease speed Decrement desired speed by
constant.

FIGURE 3.20 Event Table for Determining Set Point


Case study 3. Cruise Control

State Machine
for Toggle

Wheel rotation
Active/inactive toggle of the system
Control
Unit Engine
Event Table Desired speed
for Set Speed
Point sensor

Pulses from wheel


Clock

FIGURE 3.21 Complete Cruise Control System


注意:以上的设计仅仅是逻辑图,
实际的软件控制还需要有
类设计图。类的设计可以
设计成三个类或者三个包
Questions

问题:
Stop here!
: to show software design of An
oscilloscope (示波镜) in Tektronix, Inc to
develop a reusable system architecture for
oscilloscopes.
亮度:轨迹 聚焦:轨迹
荧光屏 电源指示灯
电源开关 校准信号
亮度调节 清晰度调节
被测信号输入
水平位移

双 通道
注意

垂直位移

GND:
输入零信号

被测信号耦合方式 DC:
AC:交流输入 直流输入 CH1或CH2:被测信号输入端口
Operational principle of oscilloscope
.
– sample electrical signals and
– displays pictures (called traces) of them on a
screen.

– perform measurements (测量) on the signals, and


– display (显示) them on the screen.
– 提供内存. supply megabytes of internal storage,
– 支持与工作站或者其它仪器的接口. support an
interface to a network of workstations and other
instruments,
. provide a sophisticated
user interface,
• a touch-panel screen with menus,
• built-in help facilities,
• color displays
接收外部信号

Waveform Clipped
S S Trace trace

Trace
Waveform Measurement
Times

FIGURE 3.8 Oscilloscopes: A Pipe-and-Filter Model


Couple(耦合): conditions external signals
a) DC: nothing gets changed
b) AC: the value should be subtracted from the
appropriate DC offset
c) Ground: the voltage value = 0
Acquire(获取波形): derive digitized waveforms
from the signals, when a trigger event is detected
by the Trigger subsystem
To-XY: converts waveforms into visual data by
scaling it and positioning/translating it
Clip: fits the visual data into a display of certain
size
.
This model agrees with the engineers' view of
signal processing as a dataflow problem,
.
It has all the advantages that pipes-and-filters
architecture should have
The main problem with the model was that it was not
clear how the user should interact with it.
– Where the user interface should locate?
– How the user will interact with it?
Use the same design as pipes-and-filter’s
architecture, with the following modifications:
a) introduce some parameters
b) add user interface
参数

FIGURE 3.8 Oscilloscopes: A Modified Pipe-and-Filter Model


:
This transformer is used to subtract a DC offset
from a signal. In this case, the user has three
choices of parameterization:
– DC, if chosen, then the signal is unchanged
– AC, if chosen, then the signal will be subtracted
by an appropriate DC offset
– Ground. if chosen, get a signal whose value is 0
volts at all times
through this, a Waveform is got from a Signal by
extracting a time slice.
• The waveform is identical to the signal, except that
it is defined only over a bounded interval that
determined by three things:
– time value delay, determines when the interval is
sampled relative to the reference time.
– time value duration, determines the length of the
interval
– a reference time, calls a trigger event.
• Display transformers (To_XY and CLIP) convert
these waveforms into visual data.

• Component To-XY: converts waveforms into


visual data by scaling it and positioning/translating
it
• Component Clip: fits the visual data into a display
of certain size
• This solution allows user inputs by associating with
each filter a control interface that allowed an
external entity to set parameters of operation for
the filter.
– For example, the acquisition filter could have
parameters that determined sample rate and
waveform duration.
• These inputs serve as configuration parameters for
the oscilloscope.
• One can think of such filters as having a "control
panel" interface that determines what function
will be performed across the conventional
input/output dataflow interface Formally.
: The parameterized
pipes-and-filters architecture allows some
aspects of the oscilloscope can be modified
dynamically by the user.

• It also explains how the user can change


oscilloscope functions by incremental
adjustments to the software.
2. : It separates
the signal-processing functions of the
oscilloscope from the user interface;
– the signal-processing software makes no
assumptions about how the user actually
communicates changes to its control
parameters.
– Designers can therefore change the
implementation of the signal-processing
software and hardware without affecting the
implementation of the user interface.
: waveforms can occupy a large
amount of internal storage, it is simply not
practical for each filter to copy waveforms every
time they process them.
: Further, different
filters may run at radically different speeds: it is
unacceptable to slow one filter down because
another filter is still processing its data.
• To handle these problems the model was further
specialized. Instead of using a single kind of pipe,
we introduced several "colors" of pipes.
– No copying some data: Some of these allowed
data to be processed without copying.
– Ignore incoming data: Others permitted slow
filters to ignore incoming data if they were in the
middle of processing other data.
Coupling kind, rate Trans Size

S S W T T
Couple Acquire To-XY Clip
Trace
Waveform
Times

Trigger subsystem Measure

Oscilloscopes: A Modified Pipe-and-Filter Model with


different types of pipes
Professor:
Yushan (Michael) Sun
Fall 2016
Contents of this lecture

1. Introduction of the abstract factory


pattern
2. Theory of the abstract factory pattern
3. Design example using the abstract
factory pattern
4. Further applications of the abstract
design pattern
我的职责是生产对象
1)获得对象a

2)a.
工厂方法模式-汽车保险的例子

1)获得产品
对象a

2)调用方法

a.
+factory: Product +Operation()

+factory: Product +factory: Product +Operation +Operation

<<create>> <<create>>
导致使用抽象工厂模式的例子
导致使用抽象工厂模式的例子
+factory: Shoes

+factory: Shoes +factory: Shoes

+factory: Suit

+factory: Suit +factory: Suit

+factory: Shirt

+factory: Shirt +factory: Shirt


导致使用抽象工厂模式的例子
导致使用抽象工厂模式的例子

Pay attention to the fact that products below


have the same structure,

we get the solution as below in the next page.


导致使用抽象工厂模式的例子

+getManSuit: ManSuit +getWomanSuit: WomanSuit


+getManShoes: ManShoes +getWomanShoes: WomanShoes
+getManShirt: ManShirt +getWomanShirt: WomanShirt

Back
+getObjA: Product 对应产品A
+getObjB: Product 与产品B

+getObjA: Product
+getObjB: Product << >>

<< >>
<< >>
• The Abstract Factory pattern takes the same
concept as the Factory method pattern does.

• An abstract factory is a class that


provides an interface to produce a family of
objects.

• In the Java programming language, it can be


implemented either as
– an interface or as
– an abstract class.
Components in abstract factory pattern
– 产品层次类:Families of related, dependent
product classes (鞋子、西装、衬衫)
– 工厂层次类:A group of concrete factory
classes that implement the interface
provided by the abstract factory class.
– 工厂层次类:Each of these factories
provides access to a particular suite of
related, dependent objects and implements
the abstract factory interface in a manner
that is specific to the family of classes it
controls.
• 当一个客户对象需要创建多个相关的层次类对象
中的一个对象,但是不需要知道哪个具体的类被
初始化了的时候,使用抽象工厂模式
• Use the Abstract Factory pattern when a client
object wants to create an instance of one of a
suite of related, dependent classes without
having to know which specific concrete class is
to be instantiated.
• What will happen if we don’t use the
abstract factory pattern?
• 如果不使用抽象工厂模式,在客户程序中
将有太多的条件语句
• If we don’t use abstract factory, the
required implementation to select an
appropriate class needs to be present
everywhere such an instance is created.
• Client objects make use of these concrete
factories to create objects and, therefore,
• do not need to know which concrete class is
actually instantiated.
1. For factory method pattern, the product is a
single product class hierarchy. For abstract
factory pattern, the product is a group of
product class hierarchies
工厂方法模式,单一的产品类;
抽象工厂模式,多个产品类
2. 工厂方法模式符合开闭原则;但是抽象工
厂模式仅仅部分地符合开闭原则
The factory method pattern follows open-
closed principle, while the abstract factory
pattern only partially follow the open-
closed principle (见下页)
• 两种情况
• 第1种情况:增加新产品子类。If you add a
符合开闭原
则的情况 +getObjA: Product
+getObjB: Product

+getObjA: Product
+getObjB: Product

If you don’t want to add a product class, but only add a concrete product in
the existing product hierarchies, this pattern follows open-closed principle
• 两种情况

• 第2种情况:

+getObjC:
Product
不符合开闭 +getObjA: Product
+getObjB: Product
原则的情况

+getObjA: Product
+getObjB: Product
+getObjC: ProductC +getObjC: ProductC

When you want to add a whole new class hierarchy productC,


this pattern doesn’t follow open-closed principle, since in both
Concrete creator classes, you need to add getObjC method Back
Query Software of Building Features

• Example of Abstract Factory Pattern


• Let us design an application to query the
features of different types of buildings .
• Consider two types of buildings: house and
(别墅), condo (公寓)

House Condo Semi detacher


独立房屋 分户出售公寓大厦 半独立楼宇
Query Software of Building Features

• Further, a building can be of either


– Super or
– Medium
category.
• Because House and Condo represent two
kinds of products and each can be classified
as super and medium, we can use abstract
factory pattern as below.
Query Software of Building Features

<create>

<<create>>

<create> <<create>>
1. From GUI, input parameter
”super” or ”medium”, and call
getFactory(c) to get a

object bf ( 子类对象)
2. Base on the parameter “house”
or “condo” input from GUI, to get
House对象: h = bf.getHouse(), or
getFactory(“super”) Condo对象 c = bf. getCondo()
3. Using h or c to get
h.getHouseInfo()
c.getCondoInfo()
获得房屋信息

h = bf.getHouse()获得了superHouse对象


create create
只知道
House or Condo
接口,但是不知道它们
的子类
Query Software of Building Features

Design reason:
• If we don’t use the abstract factory pattern,
and just call the methods in classes House
and Condo directly,
• then in the
Query Software of Building Features

• Benefits of the design:


• Responsibility separation:
• The responsibility of selecting and instantiating
an appropriate House/Condo implementer is
moved out of application objects to a separate
designated abstract factory class.

• About BuildingFactory class:


• It simply declares the required interface, leaving
the actual implementation details of class
selection and instantiation to its implementers.
Query Software of Building Features

• About client object


• It uses an instance of a concrete factory that
implements the BuildingFactory interface to
create objects representing houses of different
types and categories without having to know the
actual concrete class that needs to be
instantiated. 不需要知道初始化哪个确切的房屋
子类
• The client objects do not have to know about the
existence of these concrete factory classes.不需
要确切地知道初始化哪个工厂子类
Query Software of Building Features

The graphical user interface of Query Software of Building Features


Query Software of Building Features

How works?
1. When the Search button is clicked after a
building category and type combination is
selected, the client
invokes the static
method on the abstract
class.
2. The method
creates an appropriate factory object and
returns it as an object of type.
Query Software of Building Features

3. The factory object internally creates an


instance of an appropriate class from among
the family of buildings it controls
(SuperHouse/SuperCondo or
MediumHouse/MediumCondo) and returns it
as an object of House/Condo type.
4. 客户类 不需要知道是否存
在具体的House/Condo类
Query Software of Building Features

• The client AbstractFactoryGUI does not need to


know the existence of different concrete
House/Condo classes.
• It simply invokes methods declared by the
House/Condo interface such as
– getHouseInfo or
– getCondoInfo.
Source Code for the Building Information System

public interface House {


public String getHouseInfo();
}
Source Code for the Building Information System

public class SuperHouse implements House {


public String getHouseInfo() {
return "superHouse.html";
}
}

public class MediumHouse implements House{


public String getHouseInfo() {
return "mediumHouse.html";
}
}
Source Code for the Building Information System

public interface Condo {


public String getCondoInfo();
}
Source Code for the Building Information System

public class SuperCondo implements Condo{


public String getCondoInfo(){
return "superCondo.html";
}
}

public class MediumCondo implements Condo{


public String getCondoInfo(){
return "mediumCondo.html";
}
}
Source Code for the Building Information System

public abstract class BuildingFactory{


public static final String SUPER = "Super Class";
public static final String MEDIUM = "Medium Class";
public abstract House getHouse();
public abstract Condo getCondo();
public static BuildingFactory getFactory(String type){
BuildingFactory bf = null;
if (type.equals(BuildingFactory.SUPER)){
bf = new SuperFactory();
}
else if (type.equals(BuildingFactory.MEDIUM)){
bf = new MediumFactory();
}
return bf;
}
}
Source Code for the Building Information System

public class MediumFactory extends


BuildingFactory {

public House getHouse(){


return new MediumHouse();
}
public Condo getCondo(){
return new MediumCondo();
}
}
Source Code for the Building Information System

public class SuperFactory extends


BuildingFactory
{

public House getHouse(){


return new SuperHouse();
}
public Condo getCondo(){
return new SuperCondo();
}
}
Source Code for the Building Information System
public class AbstractFactoryGUI extends JFrame {
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(AbstractFactoryGUI.SEARCH))
{
String class = (String) cmbHouseClass.getSelectedItem();
String type = (String) cmbHouseType.getSelectedItem();
BuildingFactory bf = BuildingFactory.getFactory(class);
if (type.equals(AbstractFactoryGUI.HOUSE)) {
House hs = bf.getHouse();
String fileNm = hs.getHouseInfo();
putHouseInfoToScreen(fileNm);
}
if (type.equals(AbstractFactoryGUI.CONDO)) {
Condo cd = bf.getCondo();
String fileNm = cd.getCondoInfo();
putHouseInfoToScreen(fileNm);
}
}}
} Back
格斗类游戏软件

• 假设我们计划一款格斗类游戏软件.玩家与敌方士
兵以及怪兽进行战斗。
• 为了适应不同等级玩家的需要,游戏特地安排了
三个难度级别:
–初等级别:敌方士兵反应迟钝,怪兽步履缓慢,即便是
初学者也能够很轻松地取胜
–中间级别:敌方士兵反应适度,怪兽步履速度中等,中
级玩家有可能取胜
–高难级别: 敌方士兵反映敏捷,怪兽狰狞狡诈,就算
是高级玩家也难逃被击毙的厄运。
请应用抽象工厂模式进行设计。
格斗类游戏软件

• 在具体实现时可以先设计两个抽象产品类Fighter和
Monster,用来代表士兵和怪兽。
• Fighter: SlowFighter, MedFighter, SuperFighter
• Monster: SlowMonster, MedMonster, SuperMonster
• 注意: 用户有三种选择:初级,中级,高级
• 初级: SlowFighter, SlowMonster
• 中级: MedFighter, MedMonster
• 高级: SuperFighter, SuperMonster
格斗类游戏软件

• 为了保证这种一致性,程序员在编码时必须非常
小心,否则稍有疏忽,那些正在痛击
SlowFighter的初级游戏者一转身撞上一个
SuperMonster,肯定会败得一塌糊涂。

• 抽象工厂模式可以很好地解决这一问题,设计抽
象工厂 然后再根据不同的
难度级别依次构造 和

• 三个具体工厂,并由它们负责按照当前游戏策略
的要求去生成具体的士兵和怪兽。
Back

-speed -speed -speed


-weapon -weapon -weapon
+getAFactory(String type)
+getFighter: Fighter
+getMoster: Monster

+getFighter: Fighter +getFighter: Fighter getFighter: Fighter


+getMoster: Monster +getMoster: Monster +getMoster: Monster

-vitality -vitality -vitality


-intelligence -intelligence -intelligence
Software Architecture
软件体系结构

Professor:
Yushan (Michael) Sun
Fall 2015
显式调用的特点:调用者必须知道被调用者的类名、
构造方法(包括参数)与要调用的方法(包括参数)
Explicit invocation: the invoking object must
know the name of the class being invoked and
the method (including parameters) in the class

op1
op3

op2
事件系统使用隐式调用
Event system uses implicit invocation:

• In an event based system, an event will invoke


some procedures and the procedures will run
automatically.
Event system uses implicit invocation.
Bradcast
Register for Buy()
events Honda

The method in the object


will automatically run
once the registered event
is triggered
Broadcast
events Register for
Honda Buy()

Event-based system: event broadcast, event registration,


method being called automatically
想调用谁,
就直接调用
Pr 1
Et 1
Et 2

Proc1 中石油=15元
Pr
Proc2 中石化=10元 oc
ed
Evt1
Pr 1
oc
中国铝业
Pr ed
Evt2 oc 2
ed
中国航空 Ev 3
t1
Ev
t2
我注册
我注册

Legend: Register event Send event


广播事件

调用 调用
Source file numOfDogs=11
Bbbbbbbbbbbbbb foodAmount=7
Note: Cccccccccccccc salary=2348
Dddddddddddddd
Eeeeeeeeeeeee
Fffffffffffffffffffffffffffffffff
Gggggggggggggggggg
hhhhhhhhhhhhhhhhhhh
2. Styles of Event-based system:
Strategy of Events Handling
2. Strategy of Events Handling
2. Strategy of Events Handling

Event
事件广播 space
2. Strategy of Events Handling
2. Strategy of Events Handling
2. Strategy of Events Handling

Publish event
Subscribe
Send event
2. Strategy of Events Handling

listen

listen Event
Space listen

listen listen
2. Strategy of Events Handling
2. Strategy of Events Handling

Legend: Register event Send event


Observable watched = new Subject();
Client Observer watcher = new ConcreteObserver1();
watched.register(watcher);

<<interface>> <<interface>>
Observable Observer
register(obs: Observer)
unRegister(obs:Observer)
notifyObservers()

getState()
notifyObservers()
register(obs: Observer)
unRegister(obs:Observer) 拉模型
Diagram for general Observer pattern (no central
Observable S = new Subject();
Client Observer O = new Observer1();
S.register(O);

<<interface>>
<<interface>> Observer
Observable
register(obs: Observer)
unRegister(obs:Observer)
notifyObservers()

getState()
notifyObservers()
register(obs: Observer)
unRegister(obs:Observer)
• DESCRIPTION
• The Observer pattern is useful for designing
a consistent communication model between
– Observers: a set of dependent objects
and
– Subject: an object that they are
dependent on.
Note 1:
1. 一个主题可以有多个观察者。A subject can
have more than one such observer. Each of
these observers needs to know when the
subject undergoes a change in its state.
2. 主题保持一个动态列表,记录已经注册的观察
者The subject must maintain a dynamic list
for registering observers.
• (The subject cannot maintain a static list of such
observers as the list of observers for a given
subject could change dynamically).
• How the observer pattern works?
• Observer must register itself:
– Any object with interest in the state of the subject
needs to explicitly register itself as an observer
with the subject.
• Observable must notify the observers:
– Whenever the subject undergoes a change in its
state, it notifies all of its registered observers.
• An observer can query about the state of the
obsevable:
– Upon receiving notification from the subject, each
of the observers queries the subject to
synchronize its state with that of the subject’s.
通知观察者的两种策略:

The subject should


send the state information that the observers
may be interested in

The subject should


provide an interface that enables observers to
query the subject for the required state information
to update their state.

• 【注】观察者模式有许多变形
Advantages of the Observer pattern:
1. 可以动态添加观察者而不需要影响主题。
Different observers can be added dynamically
without requiring any changes to the Subject
class.
2. 当主题的状态或者逻辑发生变化的时候,观察
者不受影响。
When the state or logic of the subject changes,
observers remain unaffected
• Java语言环境对观察者模式的支持。
• Java API支持Observanle/Observer策略(例如:
J2SDK1.4). Java提供了以下的

Observable <<interface>>
Observer
+addObserver(observer:Observer) +update(o: Observable, e: Object)
+setChanged()
+notifyObservers(event: Object)

被观察者类 观察者接口
Observable类:在该类中,所有的三个方法
addObserver(observer:Observer),
setChanged(),
notifyObservers(event: Object)
都已经实现了。

Observer 接口。在Observer 接口中,


update(o: Observable, e: Object)
方法带有两个参数。
<<interface>>
Observable Observer
+addObserver(observer:Observer)
+setChanged()
+notifyObservers(event: Object)
某些事件

getState()

Java支持的观察者模式类图-既拉又推
Observable S = new Subject();
Client Observer O = new Observer1();
S.addObserver(O);

Observable <<interface>>
Observer
+addObserver(observer:Observer)
+setChanged()
+notifyObservers(event: Object)

event
getState()

Java支持的观察者模式-典型交互
• Observable/Observer策略工作机制
• 被观察者可以将一个观察者添加到一个list. 这也
说明被观察者同意被该观察者观察。
• setChanged()和notifyObservers()将通知观察者
主题对象的状态已经改变了,观察者对象的
update()方法将自动运行。
• 在观察者对象的update()方法中,如果需要,可
以调用被观察者中的相应方法,确切了解状态变
化的细节。
4. Observerble/Observer example

• Example: 温度转换程序设计的例子。 We try to


display temperature measures in

or

and
4. Observerble/Observer example

• In such case, we can use observer design


pattern
User defined Observerble/Observer pattern
4. Observerble/Observer
<<interface>> <<interface>>
Observable Observer
notifyObservers()
register(obs: Observer)
unRegister(obs:Observer)

notifyObservers()
register(obs: Observer)
unRegister(obs:Observer)
Observable t =
Observer c = new ();
Observer f = new ;
Client t.register(c);
t.register(f);

<<interface>>
<<interface>> Observer
Observable
register(obs: Observer)
unRegister(obs:Observer)
notifyObservers()

getState()
notifyObservers()
register(obs: Observer)
unRegister(obs:Observer)

利用观察者模式设计的温度转换程序的典型交互
4. Observerble/Observer
• Design highlights: Two interfaces
– Observable
– Observer
with exactly all of their methods claimed in
the design.

• In

– notifyObservers()
– register(obs: Observer)
– unRegister(obs:Observer)
4. Observerble/Observer
被观察者
观察者1

观察者2

观察者3
public class TemperatureGUI implements Observable{
ArrayList(<Observable>) observersList = new ArrayList(<Observable>);

public void register (Observer obs) { observersList.add(obs);}


public void unRegister(Observer obs){ observersList.remove(obs); }
public void notifyObservers(String temperature) {
for (int i = 0; i < observersList.size(); i++) {
Observer observer=(Observer)observersList.elementAt(i);
observer.update (this, temperature); //call update method in all the
//observers
}
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals(SUBMIT)){
String tem = boilerTem.getText(); //get temperature
setTemperature(tem); //set temperature to the private variable
notifyObservers(bTem); //notify the observers that the temperature has
//changed
} } } }}
public class CelsiusGUI extends JFrame implements Observer{
tempGui.register(this);

public void update( Observable subject, Object arg) {

String t = (String) arg; // 从参数传入的温度值 the temperature value

// parameter subject represents observable,object of TemperatureGUI is


// passed in from here. See how to call the update method in method
//notifyObservers in class TemperatureGUI

TemperatureGUI tg = (TemperatureGUI)subject; //从参数传入的被观


//察者对象
String option = tg.getSelectedTemExpression();

TemperatureConvertor tc = new TemperatureConvertor();


float cTem = tc.getCelsiusTemperature(option,t);
tempTextArea.setText(""+cTem);
} }
public class TestObserverObservable {
public static void main(String[] args) throws Exception {

//create an observable object


TemperatureGUI temperatureObj = new TemperatureGUI();

//Create Observer objects


CelsiusGUI cg = new CelsiusGUI();
FahrenheitGUI fg = new FahrenheitGUI();
KelvinGUI kg = new KelvinGUI();
}
}

注意:这里没有addObserver方法的调用,是因为在CelsiusGUI中,
已经有tempGui.register(this);
• 通常,在客户程序中,要做以下事情:
1)create object of observable
TemperatureGUI tempObj = new TemperatureGUI();
2)create object of observer
CelsiusGUI cg = new CelsiusGUI();
FahrenheitGUI fg = new FahrenheitGUI();
KelvinGUI kg = new KelvinGUI();
3)register observers to the observable
tempObj.register(cg);
tempObj.register(cg);
tempObj.register(cg);
4) temperatureObj.notifyObservers(bTem);
使用Java API 的Observer接口和Observable类。
本次课不做要求
Design 2: 使用Java API提供的观察者机制
Use the java built in event handling strategy. In
this design, java
– Observable class and
– Observer interface
are used, the design is as below.
TestObserverObservable

<<interface>>
Observable Observer
update(o: Observable, e: Object)
addObserver(observer:Observer)
setChanged()
notifyObservers(event: Object)

Observerble/Observer
Observable t = new ();
Client Observer c = new
t.addObserver(c);
();

Observable <<interface>>
Observer
+addObserver(observer:Observer)
+setChanged()
+notifyObservers(event: Object)

event
getState()

利用Java提供的类与接口与观察者模式计的温度转换
程序的典型交互
• 客户类. In the TestObserverObservable, use
addObserver(observer:Observer) to add an observer
CelsiusGUI, FahrenheitGUI, and KelvinGUI to the
TemperatureGUI object

• 被观察类. In class TemperatureGUI, use setChanged()


and notifyObservers() together to notify the observer
that the state of the Object TemperatureGUI has
changed, and
– then the update(o: Observable, e: Object) method in
CelsiusGUI, FahrenheitGUI, and KelvinGUI objects will
be automatically invoked to update display of
temperature.
– In the update method, in turn, observable can be
called to check the state change.
被观察者图形界面
public class TemperatureGUI extends Observable{
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals(SUBMIT)){
String tem = boilerTem.getText(); //获得用户输入温度值
setTemperature(tem);
setChanged();
notifyObservers(bTem);
//notifyObservers的实现中,调用了观察者类的
//update(Observable subject, Object arg) 方法
//温度bTem经由参数arg传入观察者
}
}
} }}
public class CelsiusGUI extends JFrame implements Observer{
private JTextArea tempTextArea;
private Container contentPane;

//此处省略了图形界面生成代码
public void update(Observable subject, Object arg) {
String t = (String) arg; //用户输入的温度数值
//参数subject代表被观察者TemperatureGUI对象
TemperatureGUI tg = (TemperatureGUI)subject;

String option = tg.getSelectedTemExpression();

TemperatureConvertor tc=new TemperatureConvertor();

float cTem = tc.getCelsiusTemperature(option,t);


tempTextArea.setText("Celsius Temp: \n"+ cTem);
}
}
public class TestObserverObservable {
public static void main(String[] args) throws Exception {

//create an observable object


TemperatureGUI temperatureObj = new TemperatureGUI();

//Create Observer objects


CelsiusGUI cg = new CelsiusGUI();
FahrenheitGUI fg = new FahrenheitGUI();
KelvinGUI kg = new KelvinGUI();

//Add observers
temperatureObj.addObserver(cg);
temperatureObj.addObserver(fg);
temperatureObj.addObserver(kg);
}
}
• 在客户类的主方法中,应该包括的内容:
1)create objects of observable
TemperatureGUI temperatureObj = new TemperatureGUI();
2)create objects of observers
CelsiusGUI cg = new CelsiusGUI();
FahrenheitGUI fg = new FahrenheitGUI();
KelvinGUI kg = new KelvinGUI();
3)register observer objects to observable object
temperatureObj.addObserver(cg);
temperatureObj.addObserver(fg);
temperatureObj.addObserver(kg);
4)notify observer
setChanged();
notifyObservers(bTem);
Professor:
Yushan (Michael) Sun
Fall 2016
1. Interface of a class
2. Introduction of the Adapter pattern
3. Class Adapter Pattern (类适配器模式)
4. Object Adapter Pattern(对象适配器模式)
5. Design Examples Using Adapter
Pattern
6. Further discussions

2
Interface of a Class

• 对象(类)的所有暴露给外界的方法的全体叫做
接口
• Objects define their interaction with the outside
world through the methods that they expose.
Methods form the object's interface with the
outside world;

• 类的接口提供外部视图
• The interface of a class provides its outside view
and therefore emphasizes the abstraction while
hiding its structure and the secrets of its
behavior.
java.lang.Math类的接口声明. 包含所有方法、常数
的声明
Field Summary
static double E The double value that is closer than any other to e, the
base of the natural logarithms.
static double PI The double value that is closer than any other to pi, the
ratio of the circumference of a circle to its diameter.

Method Summary
static double cos(double a) Returns the trigonometric cosine of an angle.
static double exp(double a) Returns Euler's number e raised to the
power of a double value.
static double log(double a)
Returns the natural logarithm (base e) of a double value.
static double sin(double a) Returns the trigonometric sine of an angle.

Back
Introduction to the Adapter Pattern

5
Introduction to Adapter Pattern

Question: there are 2 water pipes, one is


thicker than the other

Problem: Incompatible interface 6


Introduction to Adapter Pattern

7
Introduction to Adapter Pattern

220 volt
electric
8
Introduction to Adapter Pattern

220 v
electric

Answer: use an adapter.


9
Introduction to Adapter Pattern

• For software design, we often encounter


the same problem:incompatible
interface

• 在软件设计中,我们也经常会遇到类似的接
口不一致的问题

10
Introduction to Adapter Pattern

Example 1. Interface Ellipse


Conversion for an
Ellipse +Ellipse(int x, int y, int w, int h)

(56, 100, 300, 200);


(56, 100)

200

300 11
Introduction to Adapter Pattern
我们希望以如下的方式声明椭圆

b 我们需要
a 这样声明
(cx, cy) 一个椭圆

(cx, cy, a, b);

: in Java API, the existing constructor is


not compatible with what we want. 12
Introduction to Adapter Pattern
FullEllipse Wrapper
Class
+FullEllipse(int centerX, int centerY, int a, int b) 新接口

Conversion formula Ellipse


原来
(转换公式):
x = centerX-a; 接口
+Ellipse(int x, int y, int w, int h)
y = centerY-b;
w = 2*a; New Ellipse(x, y, w, h)
h = 2*b;
使用公式,转换接口

1. The constructor of class FullEllipse is initialized


by centerX, centerY, a, b
2. Inside the construcor of FullEllipse, the
constructor of class Ellipse is called 13
Introduction to Adapter Pattern

(cx, cy, a, b);

即可创建所需的按照:
椭圆中心,长班轴,短半轴
方式声明的椭圆

14
Introduction to Adapter Pattern

Example 2. Insufficient Functionality-New


Functionality is needed

Adaptee
Operation1:void

: we want to use operation1 in an existing


class called Adaptee, and also we need another
operation operation2 that is not in class Adaptee.
How to solve this problem?
15
Introduction to Adapter Pattern
• Solution 1 (解决方案1):
Modify class Adaptee to add method operation2.

– You cannot get the source code


– Even you have the source code, after you modify
the file, you need to recompile it, which may
cause some new problems.
– If this class has already been used by some users,
then you need to consider side effects of your
change.

16
Introduction to Adapter Pattern

Solution 2 (解决方案2 ):

Use an interface called Target to claim all the


operations needed, and use a class called
adapter to implement all the operations in Target.

This results in the class adapter design pattern.

Back
17
Class Adapter Pattern
类适配器模式

18
Class Adapter Pattern

新接口 <<interface>> Adaptee


Target 原接口
operation1:void
用户使 operation1:void
operation2:void
用新接
口 implement Inherit

Adapter
operation2:void

Need to write code here to implement operation2. After one writes code
for operation 2, then both operation 1 and operation 2 can be used.

Class Adapter Pattern-class Diagram (类适配器模式) 19


Class Adapter Pattern

Question: How to use this pattern?

Target tgt;
tgt = new Adapter(); Why?
tgt.operation1();
tgt.operation2();

20
Class adapter pattern

怎样使用适配器模式?
Step 1. Write an interface called Target that claims
methods operation1 and operation2.
Step2. Write a class called Adapter that
• inherits Adaptee and
• Implements interface called Target

operation1 has been automatically


implemented, and we only need to write code for
operation2 in class Adapter.

21
Class adapter pattern

the expected Java interface


: current interface for inheritance
: convert the Adaptee interface into the
Target interface and some functionalities may be
added. Adapter is a concrete class.

22
示意性代码

23
24
public class {
private static ; // use the interface
as type

public static void main (String[] args){


adp = new Adapter();
adp.
adp. ;
}
}

25
Class adapter pattern- question
• 问题: 能否同时适配两个类?
• If there are two existing classes Adaptee1 and
Adaptee2, can we still use the class adapter
pattern as below?
<<interface>>
Target Adaptee1 Adaptee2
Operation1:void Operation1:void Operation2:void
Operation2:void
Operation3:void

Adapter
Operation3:void
26
Class adapter pattern- answer

:
1. in C++, this design is , but multiple
inheritance may sometimes cause
complexity
2. In Java, this design is not allowed since
in Java, multiple inheritance is not
allowed

Back
27
Object Adapter Pattern
对象适配器模式

28
(对象适配器模式)

Adaptee
operation1:void

Question (same as before):


n operation 1 in Adaptee is what we need, but
we also need another method operation2
n However, there is no method operation 2 in
class Adaptee
1. Same question as that in using “class adapter
pattern”.
2. We now use object adapter pattern, to solve this
problem.
29
(对象适配器模式)

<<interface>> Adaptee 利用调用或者聚合


Target 的方法将peration1
operation1:void 拉入。
operation1:void 问题:怎样拉入?
operation2:void

implement Call, or aggregation


Adapter
-adaptee: Adaptee
operation1:void
operation2:void

Object adapter pattern-class diagram 30


a) Write an interface called Target that claims
methods operation1 and operation2.
b) Write a an Adapter that implements methods
operation1 and operation2 in the interface
Target
c) 怎样实现两个方法?
Ø For operation1
Inside the adapter, write code
private Adaptee v; // 是否有其它方法?
v = new Adaptee ();
v. operation1()
Ø For operation2
write new code
31
32
33
When to use the Adapter pattern?

34
Class adapter pattern- question
• 问题: 在对象适配器模式中,能否同时适配两个类?
• If there are two existing classes Adaptee1 and
Adaptee2, can we still use the object adapter pattern as
below?
<<interface>>
Target Adaptee1 Adaptee2

Operation1:void Operation1:void Operation2:void


Operation2:void
Operation3:void

Adapter
Operation1: void (在方法中调用Operation1)
Operation2: void (在方法中调用Operation2)
Operation3: void (写全新的代码)

Answer: Yes Back


35
36
使用适配器模式进行设计的例子
• Example 3. 离架软件,功能不足,欲增加
新功能。
Suppose that we have purchased an off-
shelf class InfoValidator that validates
customer information (No source code)。

The functions includes:


– Validate user name
– Validate address
– Validate area phone code
– Validate cell phone number
37
使用适配器模式进行设计的例子

• The above class provides most of the


functionalities we need, however, we still need
another function to validate social security
number (格式 ddd-dd-dddd).
• Class CusInfoValidator doesn’t contain this
function and so we need to write it ourselves.
• In such case, we can use class adapter pattern.
See the design below.

38
使用适配器模式进行设计的例子

ClientGUI

<<interface>> InfoValidator
CusInfoValidator
+isValidName( ): boolean +isValidName( ): boolean
+isValidAddress(): boolean +isValidAddress(): boolean
+isValidZipCode(): boolean +isValidZipCode(): boolean
+isValidCellPhoneNum(): boolean +isValidCellPhoneNum(): boolean
+isValidSSNNum(): boolean
implements Inherits

InformationAdapter
+isValidSSNNum(): boolean

Design using class adapter pattern 39


使用适配器模式进行设计的例子

• In this design, the functionalities we need


• isValidName( ): boolean
• isValidAddress(): boolean
• isValidZipCode(): boolean
• isValidCellPhoneNum(): boolean
• isValidSSNNum(): boolean
are all included in the interface CusInfoValidator

40
使用适配器模式进行设计的例子

设计类图的解释
• The first 4 methods are included in the off-shelf class
InfoValidator. But the last method
isValidSSNNum() is not included in InfoValidator.

• InformationAdapter is responsible for implementing


isValidSSNNum()

• Because InformationAdapter has already inherited


InfoValidator,the first 4 methods have been
implemented

41
使用适配器模式进行设计的例子

运行ClientGUI产生的用户图形界面 42
使用适配器模式进行设计的例子

• Example 4. 改变接口问题。
Customer Address Validation Problem
• Suppose that we have already had two classes:
– USAddress, a class used to validate a given
US address by using a method “isValidAddr”
– CAAddress, a class used to validate a given
Canadian address by using a method
“isValidCanadianAddr”

43
使用适配器模式进行设计的例子

• 在美国客户为主的商业网站上,允许加拿大客户
使用该网站进行交易
• A website program originally validates US
address by using class USAddress.
• Now this website also needs to validate
Canadian address because some businesses
will be expanded to Canadian customers

44
使用适配器模式进行设计的例子

45
使用适配器模式进行设计的例子
Customer类希望使用一个唯一的接口,
Customer 而不是使用两个不同的接口。
Unique interface

USAddress CAAddress
isValidAddress(addr:String, isValidCanadianAddress
zip: String, state: String): (addr:String, pcode: String,
boolean prvnc: String):
boolean

Zip: 58105-2459 pCode: H1C 3W2

The parameters in isValidAddress and


isValidCanadianAddress have different formats
46
使用适配器模式进行设计的例子

47
使用适配器模式进行设计的例子

使用类适配器模式:使用一个适配器改变CAAddress
的接口
• Need to design a Java interface called
AddressValidator
• Need an adapter class CAAddressAdapter,
which
• Inherits CAAddress class
• implements the AddressValidator interface

48
使用适配器模式进行设计的例子
Customer
<<uses>> CAAddress
<<interface>> isValidCanadianAddress
AddressValidater (addr:String, pcode: String,
prvnc: String):
isValidAddress(addr:String,
boolean
zip: String, state: String):
boolean
CAAddressAdapter
isValidAddress(addr:String,
USAddress zip: String, state: String):
boolean
isValidAddress(addr:String,
zip: String, state: String): Inside this method,
isValidCanadianAddress
boolean will be called directly
49
使用类适配器模式进行的设计
使用适配器模式进行设计的例子

Inside the method isValidAddress in class


CAAddressAdapter,
the method
isValidCanadianAddress(addr:String,
pcode: String,
prvnc: String)
is called.

50
使用适配器模式进行设计的例子

How to use the pattern?

AddressValidater av; //The type of the interface


if(user chooses US)
av = new USAddress();
else if (user chooses Canada)
av = new CAAddressAdapter();

av. isValidAddress(addr, pcode, state);

51
使用适配器模式进行设计的例子
也可以使用对象适配器进行设计
Customer
CAAddress
<<interface>> isValidCanadianAddress
AddressValidater (addr:String, pcode: String,
prvnc: String):
isValidAddress(addr:String,
boolean
zip: String, state: String):
boolean
CAAddressAdapter
isValidAddress(addr:String,
USAddress zip: String, state: String):
isValidAddress(addr:String, boolean
zip: String, state: String):
boolean 在该方法的内部,调用CAAdress
中的isValidCanadianAddress
方法
Back
53
Two types of adapter patterns

implement inherit implement Call or


aggregation

Comparison of class adapter pattern and object adapter pattern

54
关于适配器模式的讨论

适配器模式的应用主要体现在两个方面
1. 改变接口
2. 增加功能
问题: 这两个方面哪个是主要的呢?
回答: 改变接口。实际上增加功能也可以看作
是改变接口,因为增加了功能也就改变
了接口。

Back 55
Difference between class adapter pattern and
object adapter pattern:
Ø In the class adapter pattern, all the attributes
and methods are inherited
Ø In the object adapter pattern, usually, only one
or several methods are chosen to pull into the
adapter class

56
类适配器模式: 对象适配器模式:
继承全部 挑选一个或者几个
东西拉入

57
Cat Cat Dog Bird
-name: String -name: String -name: String -name: String
-sex: string -sex: string -sex: string -sex: string
-age: int -age: int -age: int -age: int
-species: String -species: String -species: String -species: String
+hunt(): void +hunt(): void +hunt(): void +fly(): void
+eat(): void +eat(): void +eat(): void +layEgg(): void
+run(): void +run(): void +run(): void +hatch(): void
+mew(): void +mew(): void +bark(): void
+climb(): void +climb(): void +fight(): void

Animal
Monster

58
• Discussion: why in the the adapter pattern, use an
interface Target as below?

新接口 <<interface>> Adaptee


Target
operation1:void
用户使用 operation1:void
新接口 operation2:void

implement Inherit

Adapter

operation2:void
• Discussion: why not design as below?

Adaptee
新接口
operation1:void

Inherit
用户使用
新接口 Adapter

operation2:void

点评: 这是一种传统的通过继承增加功能的方法。和Adapter模式中使用
接口比较,本设计没有体现面向接口编程的特点。不利于扩展。
• Answer: in the adapter pattern, an interface is used because it
can be implemented using many other classes. Example: there
are 2 implementations of the design as below.

<<interface>> Adaptee
Target
operation1:void
operation1:void
operation2:void

implement Inherit

Adapter1 Adapter2

operation2:void operation2:void

好处: 同一个接口Target,可以有不同的实现。例
如,多种加密算法的实现。
Software Architecture
软件体系结构

Professor:

Yushan (Michael) Sun


Fall 2015
Contents of this lecture

2
3
网上二手车拍卖系统的设计
• Example. software requirement: need a used car
auction software that runs on the Internet。
• This software has a graphical user interface, which
can display the car pictures, the descriptions of cars,
and the current bit price
a) 用户首先在车的列表中选择一款车。User firstly
chooses a car from a list, and then clicks on
search button
b) 该车的图片,描述,与当前拍价将在屏幕上显示.
Then the picture, descriptions and the current
bit price of the chosen car will be shown on
screen
c) 用户输入其拍价 User inputs his/her own bit
price
d) 新的拍价在另外一个视窗中显示。The new bit
price will be displayed on another window 4
网上二手车拍卖系统的设计

The prototype of the graphical user interface 5


网上二手车拍卖系统的设计

Different data displays


6
网上二手车拍卖系统的设计:方案1

• Design 1: 仅仅使用一个Java类实现全部功能
use only one java class to implement all the
functions
1) Produce user interface
2) All the business logics are in this java
class

7
网上二手车拍卖系统的设计:方案1
设计方案1:只 包含GUI,业务逻辑
JPanel
用一个Java文件 数据库访问
CarAuctionGUI

8
Design 1: use only one java GUI file to implement all the functions
网上二手车拍卖系统的设计:方案1

缺点 Drawbacks:
1. 可扩展性不好 Poor extensibility
• When new function is added, need to
recompile the whole class
• When you Modify something, need
recompile whole class
2. Only one user GUI, and actually
sometimes multiple GUIs are needed
Solution:redesign

9
网上二手车拍卖系统的设计:方案2

软件设计方案2: 将整个项目设计为两个组件
• 用户界面CarAuctionGUI:
a) 用户输入功能
b) 查询结果
• 类AuctionFunctions:
1. 从一个文件夹中提取车的信息描述文件
2. 将该文件显示到用户界面上
3. 从一个文件夹中提取车的图片文件
4. 将该图片文件显示到用户界面上
5. 将竟拍价格显示到屏幕上
6. 所有的业务逻辑方法
10
网上二手车拍卖系统的设计:方案2

CarAuctionGUI
+getSelectedCar(): String
+getBitPrice(): String

AuctionFunctions
+getSelectedCar(): String
+getBitPrice(): String
+extractCarList(): String[]
+setUpCarList(JComboBox cmbCarList,String[] carList)
+constructCarFileUrl(String carChosen): URL
+updateCarDescription(JEditorPane editorPane, URL url)
+showBitPrice(JTextArea bitShownText, String price )
+produceCarImaIcon(String carChosen): ImageIcon
+updateCarPicture(JLabel imgLabel,ImageIcon imgIcon)
#createImageIcon(String path): ImageIcon
11
软件设计方案2: 将整个项目设计为两个组件
网上二手车拍卖系统的设计:方案2

设计方案2的优点: 实现了责任分离
1. 在用户界面程序中,除了搭建所有的图形组件
外, 仅仅提供了用户输入的获取功能:
• getSelectedCar(): String
• getBitPrice(): String
2. 将所有其它的功能都放到单独的一个类
AuctionFunctions中

12
网上二手车拍卖系统的设计:方案2

设计方案2的缺点
在一个类AuctionFunctions中,集中了
– 业务逻辑
– 显示功能
– 其它的所有辅助功能
造成了接口污染

13
MVC Design Patterns

新设计方案考虑:
1. 要求在输入方面有可扩展性,例如
Ø 键盘输入,
Ø 图形界面上的按钮输入
Ø 手机、平板的触摸屏输入
2. 对于汽车信息,允许有不同的显示
Ø 图片显示
Ø 文字显示
Ø 性能分析
Ø 销售情况(柱形图,饼形图)
3. 希望将所有的业务逻辑都封装到一个类中
14
MVC Design Patterns

• 解决方法:使用Model-View-Controller (MVC)设计
模式。
• MVC (Model-View-Controller)设计模式
• MVC (Model-View-Controller)设计模式将一个互动
的应用分成3部分,
– 模型(Model),包含核心功能与数据
– 视图(View),负责用户输入,并且为用户显示信息
– 控制器(Controller),处理用户输入。

Back 15
16
MVC Design Patterns

• 定义:In software engineering,


Model–View–Controller (MVC) is an
architectural pattern that splits interactions
between users and applications into three
roles:
Ø the Model (business logic),
Ø the View (user interface), and
Ø the Controller (user input).
• This separation of concerns facilitates the
independent development, testing, and
maintenance of each role(关注点分离:模型、
视图和控制器). 17
MVC Design Patterns
• MVC设计模式将系统分成3个组件: Model,
View, Controller
<<manipulates>>
Model
改变模
<<updates>> 更新
视图 型状态

View Controller
View不负责输 用户输入
入,仅仅显示
<<uses>>
命令行
输出 Client
18

MVC设计模式的较早的应用的交互情况
MVC Design Patterns

• MVC历史
• MVC was first described in 1979 by Trygve
Reenskaug, then working on Smalltalk at
Xerox PARC (施乐帕克研究中心)

• Since the late 1990s, MVC is commonly


classified as an architectural pattern

19
MVC Design Patterns

• Components: Model, View , Controller


• Connectors: Explicit Invocation, Implicit
Invocation or other mechanisms (e.g. HTTP
protocol)

Model

View Controller

MVC模式架构图 20
MVC Design Patterns

• 模型的责任
• Model is responsible for
– Providing the data from the database and
saving the data into the data store (负责从数据
库取出数据,并且赋予数据变量).
– All the business logics are implemented in the
Model (负责业务逻辑实现).
– Data entered by the user through View are
checked in the model before saving into the
database (负责数据验证,然后将数据存入数据
库). 21
MVC Design Patterns

• 视图的责任
• View is responsible for:
– Taking the input from the user (获取用户输入)
– Dispatching the request to the controller, and
then (向controller发送处理请求)
– Receiving response from the controller and
displaying the result to the user (接收来自
Controller的反馈并将model的处理结果显示给
用户)
• Multiple views can exist for a single model for
different purposes.(一个model可能有多个View)
22
MVC Design Patterns

• 控制器的责任
• Controller is responsible for:
– Receiving the request from client (接收来自
客户的请求)
– Executing the appropriate business logic
from the Model (调用model业务逻辑方法)
– Producing the output to the user using the
View component (调用View显示执行结果)

23
MVC Design Patterns

Model
调用Model 调用Model
中的方法, 中的业务逻
获得数据 1)选择视图 辑方法
(因为要更 2)获取用户输入
新视图) View Controller

MVC模式架构图-交互情况
MVC Design Patterns

• Two principal separations:


– Separating the presentation from the
model
– Separating the controller from the view

25
MVC Design Patterns

数据更新:改变-传播机制(change-propagation)
• 如果用户通过一个view的controller改变了model,
所有的view必须反映出该改变。
• 当数据发生变化的时候,model通知所有的view,告
诉他们数据已经改变了;
• Views可以遍历model中的数据,以便发现到底是什
么改变了。然后更新显示数据。

【注】change-propagation机制保证了用户界面和模
型的一致性。这个改变-传播机制可以由观察着模式实
现。
26
MVC Design Patterns
Client
负责用 -model: Model Controller
户输入 -model: Model
-view: View -view: View View可以
-control: Controller +handleEvent 不必调用
Controller
<<interface>>
Observable
+addObservers <<interface>>
+notifyObservers
Observer
update(Observable subject): void
Model
-coreBusinessData
-observerList;
View1 View2
+setData
model:Model model:Model
+getData
control: Controller control: Controller
+addObservers
+notifyObservers +update(): void +update(): void

27
当代的一种MVC模式架构类图-使用了观察者模式
MVC的优点

1) 容易增加或者改变视图
事务逻辑被封装在Model中,所以在新增加一个视
图的时候,不必要改动模型,而是因为业务逻辑都
是一样的,所以只需要新增加一个视图类即可。

View

PictureView ChartView BarGraph PieGraph

28
MVC的优点

2) 容易独立地更新每个独立的软件模块
由于一个应用被分离为三个软件模块,因此,我
们可以独立地改变其中的一个模块,而不影响其
它两个模块。例如,一个应用的业务流程或者
业务规则的改变只需改动MVC的模型层。

3) 代码易开发易维护 Make source code more


flexible and maintainable
4) 业务逻辑更易测试 Make it very easy to test all
the domain logic. Because Non-visual objects
are usually easier to test than visual ones
29
MVC Frameworks

• J2EE:
– Struts
– Spring MVC
• PHP
– CakePHP
– Strusts4php
• C#.NET
– Girders
• Ruby on Rails Back
30
31
网上二手车拍卖系统的设计:方案3

方案3:采用MVC模式-使用观察者机制的情况,用户
输入界面和两个显示视图分别独立显示
• 将事务逻辑部分和用户界面部分分开,采用MVC模
式。设计如下:
– CarAuctionGUI,提供用户输入界面,代表用户;
– CarModel,Model部分,封装事务逻辑功能
– CarBitView,view部分,显示用户给出的拍卖价格
– CarGUIView,View部分,显示汽车图片
– Controller,controller部分,处理用户输入,调用model
和view
32
网上二手车拍卖系统的设计:方案3

用户输入界面原型(Prototype)-点击search按钮的时候
33
网上二手车拍卖系统的设计:方案3

二手车信息显示界面原型(Prototype)

34
用户输入界面原型(Prototype)-点击bit按钮的时候
35
网上二手车拍卖系统的设计:方案3

二手车当前拍卖价格显示界面原型(Prototype)

36
CarAuctionGUI
getSelectedCar():String Controller
getBitPrice():String objCarGUI:CarAuctionGUI
getCarList():String[] cm: CarModel
setUpComboBox(String[] carList):void carPrice: String
<<interface>> actionPerformed(ActionEvent e)
Observable
+register(Observer obs):void <<interface>>
+notifyObservers(): void
Observer
update(Observable subject): void
CarModel
String[] carNameList;
String bitPrice;
+setCarList(String[] cars):void
+getCarList(): String[] CarGUIInfoView CarBitInfoView
+setSelectedCar(String sCar): void
+getSelectedCar(): String model: CarModel model: CarModel
+setBitPrice(String bPrice): void +update(s): void
+getBitPrice(): String +update(s): void
+setCarFileURL(): void
+getCarFileURL(): URL
+setupImageIcon(): void
+getImageIcon(): ImageIcon
+register(Observer obs):void 37
+notifyObservers(): void 二手车拍卖系统的类图设计
CarAuctionGUI cm = new CarModel();
Main() cgiv = new CarGUIInfoView(cm);
getSelectedCar():String cbiv = new CarBitInfoView(cm);
getBitPrice():String cm.register(cgiv);
getCarList():String[]
cm.register(cbiv);
setUpComboBox(String[] carList):void
<<interface>>
Observable
+register(Observer obs):void
Controller
+notifyObservers(): void objCarGUI:CarAuctionGUI
cm: CarModel
carPrice: String
CarModel actionPerformed(ActionEvent e)
cgiv
cbiv <<interface>>
+setCarList(String[] cars):void Observer
+getCarList(): String[] update(Observable subject): void
+setSelectedCar(String sCar): void
+getSelectedCar(): String
+setBitPrice(String bPrice): void 链接
+getBitPrice(): String CarGUIInfoView CarBitInfoView
+setCarFileURL(): void 链接 cm(CarModel对象) cm(CarModel对象)
+getCarFileURL(): URL +update(): void
+update(): void
+setupImageIcon(): void 链接
+getImageIcon(): ImageIcon 链接
+register(Observer obs):void
+notifyObservers(): void 38
二手车拍卖系统的典型交互
CarAuctionGUI 在用户图形界面上,选择车名,按动Search按钮
getSelectedCar():String String selectedCar = objGUI.getSelectedCar();
cm.setSelectedCar(selectedCar);
getBitPrice():String
cm.setCarFileUrl();
getCarList():String[] cm.setupImageIcon();
setUpComboBox(String[] carList):void
cm.notifyObservers();

<<interface>>
Observable
+register(Observer obs):void
Controller
+notifyObservers(): void objCarGUI:CarAuctionGUI
cm: CarModel
carPrice: String
CarModel actionPerformed(ActionEvent e)

String[] carNameList; <<interface>>


String bitPrice; Observer
+setCarList(String[] cars):void update(Observable subject): void
+getCarList(): String[]
+setSelectedCar(String sCar): void
+getSelectedCar(): String
+setBitPrice(String bPrice): void CarGUIInfoView CarBitInfoView
+getBitPrice(): String model: CarModel model: CarModel
+setCarFileURL(): void +update(): void +update(): void
+getCarFileURL(): URL
+setupImageIcon(): void
+getImageIcon(): ImageIcon
+register(Observer obs):void 39
+notifyObservers(): void 二手车拍卖系统的典型交互
网上二手车拍卖系统的设计:方案3
设计方案3工作原理
a) 用户输入. 用户通过使用CarAuctionGUI中的Cars列表选择
待卖的车,点击Search,以便获取车的图片;然后输入拍价,
点击Bit,给出价格。
b) 捕捉用户输入. 每次点击按钮产生的事件,都被Controller对
象捕捉,然后调用actionPerformed()方法。
c) 更新模型数据. 在actionPerformed()方法中,将根据事件的
类型,分别使用setSelectedCar 或者setBitPrice 方法更新
CarModel的数据
d) Model通知View. 由于CarGUIView、CarBitView与
CarModel之间存在观察者/被观察者的关系,所以当
CarModel的状态改变了的时候,CarGUIView和CarBitView
的update()方法将被自动调用。
e) 更新View. 在update()方法中,调用CarModel的
getSelectedCar 或者getBitPrice 方法得到最新的数据,然后
根据数据,更新视图。
40
网上二手车拍卖系统的设计:方案3

• 设计要点
• CarModel实现了interface Observable,实现了方
法notifyObservers()和register(Observer obs)。
• CarGUIInfoView和CarBitInfoView实现了interface
Observer, 实现了方法update()。
• 每个CarGUIInfoView和CarBitInfoView都将自己注
册为CarModel的观察者。每当CarModel的状态改
变的时候,其方法notifyObservers将改变告诉给它
所有的观察者,观察者的update()可以自动查询
CarModel,了解到底是什么状态改变了,从而作出
响应的反应。
• 事实上,notifyObservers()的代码中,直接调用了
观察者中的update()方法。以下是代码。
41
public class CarAuctionGUI extends JFrame {
static public void main(String argv[]) {
javax.swing.SwingUtilities.invokeLater(new
Runnable() {
public void run() {
cm = new CarModel();
cgiv = new CarGUIInfoView(cm);
cbiv = new CarBitInfoView(cm);
cm.register(cgiv); // 将视图对象注册到模型
cm.register(cbiv); // 将视图对象注册到模型
CarAuctionGUI frame = new CarAuctionGUI();
}
});
} 42
class Controller implements ActionListener {
private CarAuctionGUI objCarGUI;
private CarModel cm;
private String carPrice;
public void actionPerformed(ActionEvent e){
String searchResult = null;
if (e.getActionCommand().equals(SEARCH)){
String selectedCar = objCarGUI.getSelectedCar();
cm.setSelectedCar(selectedCar); //更新模型数据
cm.setCarFileUrl();
cm.setupImageIcon();
cm.setSearchBtnClickInfo(true);
cm.notifyObservers(); //通知观察者
cm.setSearchBtnClickInfo(false);
}
if (e.getActionCommand().equals(CarAuctionGUI.BIT)){
carPrice = objCarGUI.getBitPrice();
cm.setBitPrice(carPrice); //更新模型数据
cm.setBitBtnClickInfo(true);
cm.notifyObservers(); //通知观察者
cm.setBitBtnClickInfo(false); 43
} }}
public class CarModel implements Observable{
private ArrayList<Observer> observersList;
private ImageIcon imgIcon;
private URL url;
private String[] carNameList;
private String carSelected;
private String bitPrice;
private boolean isBitBtnClicked = false;
private boolean isSearchBtnClicked = false;
static final String CARFILES = "CarFiles/";
static final String CARIMAGES = "CarImages/";
public CarModel(){
observersList = new ArrayList<Observer>();
carNameList=new String[200];
}
public void setCarList(String[] cars){
carNameList = cars;
}
public String[] getCarList(){
return carNameList; 44
}
CarModel代码续
public void setSelectedCar(String sCar){
carSelected = sCar;
}
public String getSelectedCar(){
return carSelected;
}
public void setBitPrice(String bPrice){
bitPrice = "";
bitPrice = bitPrice + bPrice;
}
public String getBitPrice(){
return bitPrice;
}
public void setCarFileUrl(){
String fileURLStr=CARFILES+carSelected+".html";
File file=new File(fileURLStr);
URI uri = file.toURI();
url = uri.toURL();
} 45
CarModel代码续
public URL getCarFileURL(){
return url;
}
public void setupImageIcon(){
String iconStr = CARIMAGES + carSelected+".jpg";
imgIcon = createImageIcon(iconStr);
}
public ImageIcon getImageIcon(){
return imgIcon;
}
public void setBitBtnClickInfo(boolean opt){
isBitBtnClicked = opt;
}
public boolean isBitBtnClicked(){
return isBitBtnClicked;
}
public void setSearchBtnClickInfo(boolean opt){
isSearchBtnClicked = opt;
}
public boolean isSearchBtnClicked(){
return isSearchBtnClicked;
} 46
CarModel代码续

public void register(Observer obs){


observersList.add(obs);
}
public void notifyObservers() {
for (int i = 0; i < observersList.size(); i++) {
Observer observer = (Observer)
observersList.get(i);
observer.update(this);
}
}
protected ImageIcon createImageIcon(String path){
URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
return null;
}
}} // End of class 47
class CarBitInfoView extends JFrame implements Observer{
private JLabel bitLabel;
private JTextArea bitText;
private CarModel model;
private JScrollPane textPane;
public CarBitInfoView(CarModel cmodel) {
model = cmodel;
bitLabel = new JLabel("Bits offered:");
bitText = new JTextArea(4, 20);
bitText.setFont(new Font("Serif", Font.PLAIN, 14));
JScrollPane textPane = new JScrollPane(bitText);
Container contentPane = getContentPane();
contentPane.add(bitLabel, BorderLayout.NORTH);
contentPane.add(textPane, BorderLayout.CENTER);
setVisible(true);
}
48
//CarBitInfoView代码续
public void update(Observable subject){
if((subject==model)&&(model.isBitBtnClicked())){
//从model获得数据
String sCar= model.getSelectedCar();
String pr = model.getBitPrice();
//显示在视图上
bitText.append("\n Bit price for "+ sCar + "="+ pr);
}
}
}// end CarBitInfoView

49
public class CarGUIInfoView extends JFrame
implements Observer{
private JEditorPane editorPane, imagePane, filePane;
private JSplitPane splitPane;
private JLabel imgLabel;
private CarModel model;
public CarGUIInfoView(CarModel cmodel){
model = cmodel;
buildUpScrollGUI();
}
public void update(Observable subj){
if((subj==model)&&(model.isSearchBtnClicked())){
URL url = model.getCarFileURL();
editorPane.setPage(url);
//从model获得数据
ImageIcon imIcon = model.getImageIcon();
imgLabel.setIcon(imIcon); //显示在视图上
imgLabel.validate();
}
}} Back 50
Professor:
Yushan (Michael) Sun
Fall 2016
Contents of this lecture

1. Introduction of the bridge pattern


Introduction of the Bridge Pattern
军队机构设置

沈阳军区指挥部 抽象
部分
作战处 后勤处 实现
部分

陆战团 炮团 工兵团

将抽象部分与实现部分分开的军队机构设置
Design 1 (设计1,flat 设计)

Coffee

MedMilkCoffee MedFragCoffee SuperSizeFragCoffee


Design 2 (设计2,增加新的层次)

Coffee

MedSize SuperSize

MFragCoffee SFragCoffee
Extendibility (可扩展性不好)

Coffee

MedSize SuperSize

MFragCoffee MJavaCoffee SFragCoffee SJavaCoffee


Design 3 (设计3,将抽象部分与实现部分分开)
Solution: divide the class hierarchy into two class hierarchies

CoffeeSize

MedSize SuperSize
CoffeeKind

MilkCoffee FragrantCoffee

New design: In classes MediumCoffee or SuperSizeCoffee, call


MilkCoffeeImp or FragrantCoffeeImp
Extendibility has been improved (可扩展性增强了)
CoffeeSize

SmallSize MedSize SuperSize

CoffeeKind

MilkCoffee FragrantCoffee JavaCoffee

Advantage: One can add new classes in either dimension


without affecting other classes。在两个维度上可以自由地添
加类,而不会影响到其它的类
Back
Imp (保持了实现部分的 reference)

();

OperationImp()

() ()
桥模式的组件 (Participants)
• Abstraction
– defines the abstraction's interface.
– maintains a reference to an object of
type Implementor.
• RefinedAbstraction
– Extends the interface defined by
Abstraction.
• Defines the interface for implementation
classes.
• This interface doesn't have to correspond
exactly to Abstraction's interface; in fact
the two interfaces can be
– The Implementor interface provides
only primitive operations(实现接口仅
提供原始操作)
– The Abstraction defines higher-level
operations based on these primitives
(抽象接口定义基于原始操作的高层操
作)
The ConcreteImplementors:
– ImplementorA and
– ImplementorB
implement the Implementor interface and
defines its concrete implementation.
桥模式的优点

.
An implementation is not bound permanently to
an interface
– The implementation of an abstraction can be
configured at run-time (实现部分动态配置)
– Decoupling Abstraction and Implementor also
eliminates compile-time dependencies on the
implementation (取消编译时对实现部分的依赖)
– Changing an implementation class doesn‘t require
recompiling the Abstraction class and its clients
(改变实现类不需要重新编译抽象类与客户类)
2. 改善了可扩展性。E
You can extend the Abstraction and
Implementor hierarchies independently.

3. 对用户隐藏实现细节。
.
You can shield clients from implementation
details, like the sharing of implementor
objects and the accompanying reference
count mechanism (if any).
: Use the Bridge pattern when you want
to avoid a permanent binding between an abstraction
and its implementation.
– e. g. when the implementation must be selected
or switched at run-time.
桥的一种功能
上海 石家庄

长江大桥 北京

武汉 太原

一座桥与6条路,一共有 2 X 3 = 6 种走法
桥接模式的典型交互
CoffeeKind cKind = new MilkCoffee();
Client CoffeeSize cSize = SuperSize(cKind);
cSize.getPrice();

cSize.getPrice();
return 1.5*1.2元
CoffeeSize

MedSize SuperSize
+getPrice() +getPrice() CoffeeKind
cKind.price()

return 1.2元
MilkCoffee FragrantCoffee
+price() +price()

桥接模式的典型交互-咖啡机程序的例子 Back
应用桥模式设计的例子

【例2】考虑一个自动茶水销售机的例子,该
机器销售的茶水价格与两个维度:杯子大小
与茶叶品种有关。
–杯子的体积上暂时分为中杯,大杯;
–在茶叶品种上,分为红茶,和绿茶。
应用桥模式设计的例子

按照桥模式设计,类图如下。

TeaSize ClientTeaGUI

MediumCup SuperCup
+getPrice() +getPrice()
TeaKind

RedTea GreenTea
+price() +price()
桥接模式的典型交互
TeaKind tKind = new RedTea();
Client TeaSize tSize = SuperCup(tKind);
tSize.getPrice();
tSize.getPrice();
return 1.5*1.2
TeaSize

MedCup SuperCup
+getPrice() +getPrice() TeaKind
tKind.price()

return 1.2
RedTea GreenTea
+price() +price()

茶水程序的典型交互情况
应用桥模式设计的例子
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals ( FINDPRICE )) {
String size = getTeaSize(); //获得用户输入:杯子大小
String kind = getTeaKind(); //获得用户输入:茶种类
//Create a TeaKind object
if( kind.compareTo(GREENTEA)==0 )
tKind = new GreenTea(); 创建TeaKind对
if( kind.compareTo(REDTEA)==0 ) 象
tKind = new RedTea();
if(size.compareTo(SUPERCUP)==0)
tSize = new SuperCup(tKind);
if(size.compareTo(MEDIUMCUP)==0) 创建TeaSize对象
tSize = new MediumCup(tKind);
float price = tSize.getPrice();
}
}
}
应用桥模式设计的例子
抽象接口类
public interface TeaSize {
public abstract float getPrice();
}
抽象部分子类
public class MediumCup implements TeaSize{
private TeaKind tk;
public MediumCup (TeaKind tKind){
tk = tKind;
}
public float getPrice(){
float teaPrice = tk.price();
return teaPrice;
}
}
应用桥模式设计的例子

抽象部分子类
public class SuperCup implements TeaSize{
private TeaKind tk;
public SuperCup (TeaKind tKind){
tk = tKind;
}
public float getPrice(){
float teaPrice = 1.5f * tk.price();
return teaPrice;
}
}
应用桥模式设计的例子

实现部分的抽象接口。
public interface TeaKind {
public abstract float price();
}
实现部分的实现类。
public class RedTea implements TeaKind{
private final float PRICE = 3.0f;
public float price(){
return PRICE;
}
}
应用桥模式设计的例子

实现部分的实现类。
public class GreenTea implementsTeaKind{
private final float PRICE = 2.0f;
public float price(){
return PRICE;
}
}
应用桥模式设计的例子

• 【例3】. 特工信息系统。The following design


represents an agent information system. The
agent information is encrypted and saved into
text file or a database.
• There are two ways to encrypt agent’s name and
code number, which are represented by classes
– EncryptedInfo1 and
– EncryptedInfo2.
应用桥模式设计的例子

writer: MessageWriter writer: MessageWriter


加密算法:折叠算法
1.将26个英文字母按照顺序排列,加密的时候,以
折叠的方式进行:az, by, ...,mn
2.大写字母也是如此。大写字母加密为大写字母。
3.数字加密也以此方式进行
09,18,27,36, 45

a b c d e f g h i j k l mn o p q r s t u v w x y z

0 1 2 3 4 5 6 7 8 9
加密算法:分组互换算法
1.将26个英文字母按照顺序排列,按照如下方式两
两分成一组,本组内部 加密的时候互换:ab,
cd,…, wx, yz。
2.大写字母的加密方式也是如此,大写字母加密为
大写字母。
3.数字加密:01, 23,45, 67,
89

a b c d e f g h i j k l mn o p q r s t u v w x y z

0 1 2 3 4 5 6 7 8 9
应用桥模式设计的例子

writer: MessageWriter writer: MessageWriter writer: MessageWriter

Back
思考题

• 是否可以将在抽象工厂模式中房屋信息系
统的例子改为由桥接模式设计
• 是个2维度问题
• Category: super, medium
• Kind: house, condo, semi detacher
Software Architecture

Lecture 6. Layered Architecture

Professor:
Yushan (Michael) Sun
Fall 2015
3. Comparison of 3 Layer Architecture
with MVC Architecture
Layer 5

Layer 4

Layer 3

Layer 2

Layer 1

Layer 0 (Hardware) 调用 返回

Layered architecture
Provide application services
7. Application layer for file transfers, email, Telnet,
FTP, etc

Format and encrypt data


6. Presentation layer to be sent across a network

defines how data


conversations are Set up, or stop data conversations,
started, controlled 5. Session layer between the applications at each end.
and finished

ordering and reassembly Transfer data between end systems.


of packets that may have 4. Transport layer Error recovery and flow control.
been broken up Ensure complete data transfer

checks the destination


create virtual circuits to transmit
address and passes the 3. Network Layer data from node to node.
data to layer 4.

2. Data Link layer Encode data packets into bits

1. Physics layer Send data on a carrier


4. Application layer telnet, ftp, http

3. Transport layer 发送端,中间端,

2. The internet layer ip

1. Web interface
supports
designs based on increasing levels of
abstraction.
– This allows implementers to partition a complex
problem into a sequence of incremental steps.
supports
enhancement.
– each layer interacts with at most the layers below
and above,
– changes to the function of one layer affect at
most two other layers.
• 三层架构是近年来经常使用的软件体系结
构。该体系结构可以分为通用的3层架构与
运行在互联网上的三层架构软件。
Ø运行在互联网上的三层架构被称为三层客户端-
服务器(3-tired Client/server)架构
Ø通用三层架构。本节要讲述的是通用的三层架
构。
Presentation
Layer

Application
Layer

Permanent Data
Storage Layer Database

传统的三层的层次体系结构
• 显示层(Presentation layer):
Ø显示层通常包括用户图形界面,用于用
户输入、用户请求与显示用户请求的返
回结果等。
Ø显示层调用应用层组件的过程,函数或
者方法。但是应用层从来不会调用显示
层的功能。
• 应用层(Application layer):或者称为业务逻辑
(Business Logic)层。主要包括应用的业务逻辑,
实现了应用的商业功能。
Ø该层的组件封装了应用的核心数据与功能。
Ø在该层中,如果要访问数据库或者要将程序运
行中产生的数据存储到数据库,必须调用永久
数据存储层的相应的数据库访问方法,而不能
直接访问数据库。
• 永久数据存储层(Permanent Data Storage
layer):该层包含数据库的访问与将永久数据存
储到数据库中的功能。
Ø在Java实现中,该层包含了利用JDBC写的数
据库访问代码。
Ø该层不能调用应用层与显示层,而只能将执行
应用层的请求对数据库的访问结果返回给应用
层。而应用层有可能将该数据返回给显示层。
三层层次架构与MVC软件体系结构的比较
三层层次架构与MVC软件体系结构的比较

• 在形式上,三层架构类似于MVC 架构,都是由
三部分软件模块组成的,但是实际上它们是不同
的。

• 两种架构相似之处如下:
a) 都是由三部分软件模块组成的
b) 三层架构的显示层与MVC架构的View类似;
c) 三层架构的应用层与MVC架构的Model类似。
三层层次架构与MVC软件体系结构的比较

Presentation
Layer

Controller
Application
Layer

View Model
Permanent Data
Storage Layer

Database Database

3层层次架构与MVC架构
三层层次架构与MVC软件体系结构的比较
• 三层体系结构与MVC体系结构的区别如下:
• 区别1:各个模块之间的调用关系不同
Ø三层架构的一个根本原则是显示层不能直接越过
应用层直接调用永久数据存储层的代码。首先显
示层必须调用应用层,然后再由应用层的相关的
方法转而调用永久数据存储层。不允许有相反方
向的调用。因此,三层架构的交互是线性的;
ØMVC架构的程序组件之间的交互是三角形的:
View对象发送更新给Controller对象,Controller
对象更新Model对象,并且View对象直接地从
Model对象得到更新。
三层层次架构与MVC软件体系结构的比较

• 区别2:对数据库的访问方式不同。
Ø三层架构指定一个永久数据访问层,所有对数
据库的访问均有此层承担;
ØMVC架构没有指定专门的数据库访问模块,一
般的情况下是由Model直接访问数据库,但是
也没有排除Controller中直接访问数据库的可能。
三层层次架构与MVC软件体系结构的比较

Presentation
Layer

Controller
Application
Layer

View Model
Permanent Data
Storage Layer

Database
Database

3层层次架构与MVC架构访问数据库的情况
三层层次架构与MVC软件体系结构的比较

• 区别3:关于控制模块(Controller)。
ØMVC架构中存在一个专门的Controller模块;
Ø而层次架构中通常没有这样专门的模块。事实
上,很多设计者在层次架构中的应用层里面单
独地指定一个类似的控制模块。
三层层次架构与MVC软件体系结构的比较

Presentation Layer 很多设计者在层次架构


中的应用层里面单独地
设计一个Controller模
Controller 块,其主要责任是接收
从显示层输入的用户请
Application Layer 求,然后根据请求的类
型,决定调用应用层的
其它组件。
Permanent Data Storage Layer

Database
三层层次架构与MVC软件体系结构的比较

• 关于观察者模式在三层架构 与 MVC架构 中的使



Ø在三层架构中,可以在应用层与表示层之间,
使用观察者模式:将应用层作为被观察者,将
表示层作为观察者。其目的是一旦应用层的状
态改变的时候,及时通知表示层,以便及时刷
新用户图像界面。
Ø在MVC架构中,可以在Model与View之间使用
观察者模式: Model作为被观察者, View作为
观察者。一旦Model的状态改变的时候,及时
通知View,以便及时刷新View。
Presentation Layer
Observer
Controller

Observable
Observer Observable
Application Layer
View Model

Permanent Data
Storage Layer

Database
Database

使用观察者模式的3层层次架构与MVC架构
三层层次架构与MVC软件体系结构的比较

• 【注】在3层架构中,应用层与表示层之间
,使用观察者模式。必然导致应用层对显
示层的调用(notifyObservers())。这违反了
层次架构的原则。但是考虑到采用观察者
机制更新图形界面的效率,以上的小小的
“违规”也是值得的。
2. Case Studies

:
2. Case Studies
2. Case Studies
【例1】桌面版银行业务系统。
Ø 设计并实现一个桌面版的银行业务系统。功能:
l存款;
l取款;
l新开账户;
等等。
Ø 在账户类型方面,设置了
l定期存款账户与
l支票账户。
Ø 该系统采用层次结构设计如下图所示。
AccountManager
显 使用了生成器
示 GUIDirector GUIBuilder (Builder)设计模式

NewAccountGUI ExistAccountGUI

BankAccount


层 SavingsAccount CheckingAccount

数据
库访 DBInteractions
问层

应用层次架构设计的
Database
桌面版的银行业务系统
2. Case Studies
• 该软件被设计为三层架构,包括显示层,应用层,
数据库访问层。
Ø在显示层,出于要产生并且在不同的用户界面
之间的切换的需要,采用了builder设计模式。
Ø在应用层,封装了银行账户的核心功能部分,
包括各种类型的账户与相应的功能。
Ø在永久数据存储层包括用于访问数据库的
JDBC代码。在数据库的实现中采用Microsoft
Access数据库。
• 桌面版的银行业务系统的设计类图如下图所示。
AccountManager BankAccount
-name:String
GUIDirector GUIBuilder -acctNumber: String
-balance: double
+deposit (double amount, String nowDate)
NewAccountGUI ExistAccountGUI +withdraw (double amount, String nowDate)
+transfer(8 parameters): void
+updateTransactionDB(6 parameters): void
+createNewAcct(6 parameters): void
+isExistingCustomer(3 parameters): Boolean
+generateAccountNumber(String acctType):String
显示层 +calculateInterest(4 parameters): double

应用层 SavingsAccount CheckingAccount


-balance: double -balance: double
-interestRate: double -interestRate: double
+deposit () +deposit ()
+withdraw () +withdraw ()

永久数据访问层
DBInteractions
+isExistingCustomer(String acctType, String acctHolder, String acctNum): boolean
+isExistingAcctNum(String acctType, String acctNum): boolean
+getExistCustomerBalance(String acctType, String acctHolder, String acctNum): double
+retrieveDate (String tableName , String cusName, String acctNumber): String
+retrieveInterestRate (String tableName , String cusName, String acctNumber): double
+retrieveEarnedInterest (String tableName , String cusName, String acctNumber): double
+updateTransDB (String name, String acctNum, String acctType, String transType, double transAmount, String date): void
+createNewAcct (String name, String acctNum,String acctType, double interestRate, double balance, String date): void
+executeDeposit (String cusName, String tableName, String acctNumber, double amount, double interestRate, double nowInterestTotal, String date): void
+executeWithdraw (String tableName , String cusName, String acctNumber, double nowInterestTotal, double amount): void
+executeDelete(String sql): void
2. Case Studies

银行系统用户图形界面
2. Case Studies
2. Case Studies

• 【例2】自动化软件测试平台
2. Case Studies
• 在本例中,我们考虑针对一组排序程序进行测试的
软件。该测试软件被设计成5层。
–用户图形界面层:用于用户选择测试案例,用户
输入,以及观察被测试的软件是否发生错误
–测试逻辑层:包含进行各种测试逻辑软件包,该
层选择执行某测试案例
–测试案例层:软件测试工程师所编写的测试案例
程序都部署在该层,调用某个或者几个被测试程

–被测试软件层:包含所有的被测试软件
–数据库访问层:负责将测试历史数据写入数据库
2. Case Studies
用户界面层 User Interface

测试逻辑层 Unit Test Functional Test Performance Test

测试案例层 Test case1 Test case 2 … Test case N

被测软件层 Program 1 Program 2 … Program K

数据库访问层 JDBC ODBC DAO … ADO

软件自动测试软件体系结构图
2. Case Studies
TestingGUI
<<interface>>
Testcase ResultVerification
+execute(int len); +isResultCorrect(int[] arr)
+getTimeTaken()

TestcaseBubble TestcaseHeap TestcaseInsertion TestcaseQuick


+execute(int len); +execute(int len); +execute(int len); +execute(int len);
+getTimeTaken() +getTimeTaken() +getTimeTaken() +getTimeTaken()

<<interface>>
SortAlgorithm
sort(int[] nums): int[]

BubbleSort HeapSort InsertSort QuickSort


+sort(int[] a) +sort(int[] a) +sort(int[] a) +sort(int[] a)

应用层次架构设计的软件测试工具(功能测试):一个测试案例的情况
2. Case Studies

初始用户图形界面
2. Case Studies
在此用户图形界面上,可以选择待执行的测试案例,例
如,选择执行测试案例2得到以下的输出。

当选择了测试案例2并且执行测试的情况
2. Case Studies
2. Case Studies

• The Mobile Robot Laboratory is engaged in long-


term basic research in
– Perception (感知, see, feel suroundings)
– control and
– planning
for robots that navigate through complex indoor
and outdoor spaces.
2. Case Studies

(海王星)
(天王星)
2. Case Studies

Neptune (海王星) Uranus (天王星)


2. Case Studies
Supervisor

Global Planning
Control

Navigation Manage the navigation of the robot

Real-world Modeling

Sensor Integration

Sensor Interpretation

Robot Control

Environment
2. Case Studies
the lowest level, reside the robot control
routines (motors, joints, etc.).
, the analysis of
the data from one sensor, and
, the combined
analysis of different sensor inputs

is concerned with maintaining the robot's


model of the world.
manages the navigation of the robot.
schedule and plan the robot's actions.
Dealing with problems and replanning
is also part of the level-7 responsibilities.
2. Case Studies
:

. Actually,
2. Case Studies
:
• Abstraction levels defined by the layered
architecture
– provide a framework for organizing components
– framework succeeds because it is precise about the
roles of the different layers
• Major drawbacks
– model breaks down when taken to the greater level of
detail demanded by an actual implementation.
– Communication patterns in a robot not likely to follow
the orderly scheme implied by the architecture.
Lecture 6
Contents of this lecture

1. Concept of the façade design pattern


2. Design example using the façade pattern
3. Properties of the façade pattern

5. Comparison of facade pattern and the


adapter pattern
6. Comparison of the examples
Concept of the Façade Pattern
Introductory example 1: companies and government
sections

Some companies go to government sections for approval of documents


A lot of interactions involved
Now we introduce a receptionist

Receptionist 接待员

A company can just go to the receptionist, which in turn


will go to the related government sections
某电子工程师要开发
一个电子器材管理系
ElectronicEquipManagement 统。使用一个类库。
不知道怎样使用类库。
困惑!

How to solve this problem?


现在,程序容易写了。
只需要在客户类里面
调用门面类的功能即
ElectronicEquipManagement 可。
雇用某高级软件工程师,写
了一个门面类(外观类),
提供电子器材管理系统所必
备的功能。
This idea can be used in software development

Back
Design Example Using the Façade Pattern
【例1】(家庭安全系统) A Home Security System
Home health and security system is a comprehensive
system, which is in charge of fire protection, security,
health etc.
– 火灾报告:When fire occurs, the system can call
the fire brigade automatically
– 疾病报告:When a family member gets acute
disease, the system can call a hospital
automatically
– 抢劫报告:When a family is robbed, the system
can promptly inform a police station
Existing library.
Suppose that there exists a library for use,
• with many existing classes
• that can be called to fulfill the task.
A library for security system
Question: How to design the home security
program?

Design 1: Write the application code that


directly invokes the library.

The design is in the next page.


本设计的缺点:
• Client class has very high coupling with the
library;
• A non professional software developer may be
confused by so many classes in the library;

• We redesign the system using the façade


pattern class as below.
使用门面
模式的设

Here, the client program only invokes the class, calling
functions activate or deactivate (without having to know the complex
functions in all the other classes behind).
Java源代码
public class Client {
private static SecurityFacade security;
public static void main(String[] args){
security = new SecurityFacade();
security.activate();
}
}
public class SecurityFacade {
public void activate() {
camera1.turnOn();
camera2.turnOn();
light1.turnOn();
light2.turnOn();
light3.turnOn();
ss.activate();
ts.activate();
cs.activate();
hs.activate();
ws.activate();
wss.activate();
pc.activate();
hc.activate();
fc.activate();
alarm.activate();
}
public void deactivate() {
camera1.turnOff();
camera2.turnOff();
light1.turnOff();
light2.turnOff();
light3.turnOff();
ss.deactivate(); 门面类在这里实
ts.deactivate(); 现对类库的调用
hs.deactivate();
ws.deactivate();
wss.deactivate();
pc.deactivate();
hc.deactivate();
fc.deactivate();
alarm.deactivate();
}
}
public class Alarm {
public void activate(){
System.out.println("Activating the alarm.");
}
public void deactivate(){
System.out.println("Deactivating the alarm.");
}
public void ring(){
System.out.println("Ring the alarm.");
}
public void stopRing(){
System.out.println("Stop the alarm.");
}
}
public class Camera {
public void turnOn(){
System.out.println("Turning on the camera.");
}
public void turnOff(){
System.out.println("Turning off the camera.");
}
public void rotate(int degrees){
System.out.println("Rotating the camera by " +
degrees + "degrees.");
}
}
public class Light {
public void turnOn(){
System.out.println("Turning on the light.");
}
public void turnOff(){
System.out.println("Turning off the light.");
}
public void changeBulb(){
System.out.println("Changing the light-
bulb.");
}
}
public class {
public void activate(){
System.out.print( "Activating HumidSensor.");
}
public void deactivate(){
System.out.print("Deactivating HumidSensor.");
}
public void trigger(){
System.out.print(" HumidSensor has been
triggered.");
}
}
public class {
public void activate(){
System.out.print("Activating SmokeSensor.");
}
public void deactivate(){
System.out.print("Deactivating .");
}
public void trigger(){
System.out.print(" has been
triggered.");
}
}
public class {
public void activate(){
System.out.print("Activating .");
}
public void deactivate(){
System.out.print("Deactivating .");
}
public void trigger(){
System.out.print(" has been
triggered.");
}
}
public class {
public void activate(){
System.out.print("Activating WindowSensor.");
}
public void deactivate(){
System.out.print("Deactivating WindowSensor");
}
public void trigger(){
System.out.print("WindowSensor has been
triggered.");
}
}
public class {
public void activate(){
System.out.print("Activating ChemicalSensor.");
}
public void deactivate(){
System.out.print("Deactivating ChemicalSensor.");
}
public void trigger(){
System.out.print("ChemicalSensor has been
triggered.");
}
}
public class {
public void activate(){
System.out.print("Activate WaterSafeSensor.");
}
public void deactivate(){
System.out.print("Deactivate WaterSafeSensor.");
}
public void trigger(){
System.out.print(" WaterSafeSensor has been
triggered.");
}
}
public class {
public void activate(){
System.out.print("Activating .");
}
public void deactivate(){
System.out.print("Deactivating PoliceCaller."); }
public void trigger(){
System.out.print("PoliceCaller has been
triggered.");
}
}
public class {
public void activate() {
System.out.print("Activating .");
}
public void deactivate(){
System.out.print("Deactivating .");
}
public void trigger() {
System.out.print(" is triggered.");
}
}
public class {
public void activate(){
System.out.print("Activating .");
}
public void deactivate() {
System.out.print("Deactivating .");
}
public void trigger() {
System.out.print(" is triggered.");
}
}

Back
门面模式的意图
Intent of the
• Provide a unified interface to a set of
interfaces in a subsystem.
– Facade defines a higher-level interface that
makes the subsystem easier to use.
Use the Facade pattern when you want to provide
a simple interface to a complex subsystem.
– Subsystems often get more complex as they
evolve.
– A facade can provide a simple default (默认,
缺省)view of the subsystem that is good
enough for most clients.
1. (解耦)Reduce couplings between a client class and the
classes in use.
– In case there exist many dependencies between
clients and the implementation classes of an
abstraction,
– a facade pattern can be used to
and other subsystems, thereby
promoting subsystem independence and portability.

Client Client1 Client2

Façade
By using a façade pattern, you can
layer your subsystems.
– Use a facade to define an entry point to each
subsystem level.

Façade 1 Façade 2 Façade 3

In order to use bad-formed but useful classes, one can


write one or several façade classes
缺点(Disadvantages):
• Use of the façade pattern makes the facade
harder to use for clients that don't need to
customize it.
– In this case, the client can use the subsystem
directly.

Back
Another Example-account management

【例2】 (信息验证系统) Information Validation

Suppose that there are three classes


– Account,
– Address and
– CreditCard
available in the library,
each with its own methods for validating and saving
the respective data.
CreditCard
Address Account cardType:String
cardNumber:String
address:String firstName:String cardExpDate:String
city:String lastName:String
state:String
isValid():String
isValid():boolean isValid():boolean save():String
save():boolean save():boolean getCardType():String
getAddress():String getFirstName():String getCardNumber():String
getState():String getLastName():String getCardExpDate():String

There exist 3 classes for validating Address, Account, and CreditCard info
• We need to build a client Gui to
– input the customer data,
– validate the information and
– save the user information to three text files:
• AccountData.txt,
• AddressInfo.txt and
• CreditCardInfo.txt
设计1: 不使用门面模式的设计,客户程序直接调用
类库中的方法
UserGUI Address
address:String
city:String
state:String
isValid():boolean
save():boolean
getAddress():String
getState():String

CreditCard
cardType:String
Account cardNumber:String
firstName:String cardExpDate:String
lastName:String isValid():String
isValid():boolean save():String
save():boolean getCardType():String
getFirstName():String getCardNumber():String
getLastName():String getCardExpDate():String
在这样的设计下,客户类UserGUI的责任
• In order to validate and save the input data, the
client UserGUI would:
– Create objects of Account, Address and
CreditCard
– Validate the input data using these objects
– Save the input data using these objects

UserGUI and
the class library
设计2.使用门面模式的设计

need a façade class Address


to customize the Address:String address:String
City:String
functionalities that State:String
city:String
will be used by the cardType:String state:String
client class UserGUI cardNumber:String isValid():boolean
cardExpDateString save():boolean
Fname:String getAddress():String
Lname:String
getState():String
UserGUI CreditCard
cardType:String
cardNumber:String
cardExpDate:String
isValid():String
Account save():String
firstName:String getCardType():String
lastName:String getCardNumber():String
isValid():boolean getCardExpDate():String
save():boolean
getFirstName():String
getLastName():String
• CustomerFacade offers a higher level, simplified
interface to the subsystem consisting of customer
data processing classes (Address, Account and
CreditCard).
• CustomerFacade class offers a higher level
method saveCustomerData.

About UserGUI
• UserGUI can use the higher level, more simplified
interface offered by the CustomerFacade object to
validate and save the input customer data.
哈哈,我的任务减轻了
In the revised design, to validate and save the input
customer data, the Client class UserGUI needs to:
a) 创建门面对象。Create or an instance of the
facade class CustomerFacade
b) 给门面对象传送数据。 Send the data to be
validated and saved to the CustomerFacade
instance
c) 调用门面方法。Invoke the saveCustomerData
method on the CustomerFacade instance
CustomerFacade

• The CustomerFacade handles the details of


– creating necessary Subsystem objects and
– calling appropriate methods on those objects
to validate and save the customer data.
• The UserGUI is no longer required to directly
access any of the subsystem (Account, Address,
And CreditCard) objects.
• When the client UserGUI is run, it displays the user
interface shown below.
Example of Ellipse

【例3】椭圆问题,增加新功能。
• Java SDK has a class named Ellipse2D.double,
which provides some simple ellipse operations.
• The constructor of Ellipse2D.Double(double x,
double y, double w, double h)
• Parameters:
– x, y: top left-hand corner coordinate,
– w: width
– h: height.
Example of Ellipse

Java 的Ellipse2D类没有提供足够的椭圆方法
• For math professionals, the functions are
obvious insufficient.
• E.g., this class has not provided
– the focal point(焦点),
– the eccentricity (离心率)
and so on basic mathematical functions.
Example of Ellipse

想设计一个新的类,可以使用该类以不同的
方法创建椭圆;提供足够的椭圆方法,
1) we design a class
GeneralizedEllipse,
By using this class,
– 3 kinds of initializations of an ellipse
can be realized.
– New ellipse methods are provided
Example of Ellipse

2) We try to generalize the class


Ellipse2D.Double to add the functions we
want by creating a class called
EllipseOperations which extends
Ellipse2D.Double
3) Next, we write a class named EllipseGraph,
to show a graph with supplied parameters
topLeft, topRight, width, height
Example of Ellipse
The functionalities include:
+initializeOvalByCorner(double xCorner, double yCorner,
double xLen, double yLen)
+initializeOvalByCenter(double xCenter, double yCenter,
double xRadius, double yRadius)
+initializeOvalByRectangle(double xLeft, double xRight,
double yBottom, double yTop)
+drawOval(): EllipseGraph 画椭圆
+getOvalArea(): double 计算椭圆面积
+getOvalPerimeter():double 计算椭圆周长
+getEccentricity (): double 计算椭圆离心率
+getFocalPoints(): Point2D[] 计算椭圆焦点
+getCornerX(): double 计算椭圆外接矩形左上角x-坐标
+getCornerY(): double 计算椭圆外接矩形左上角y-坐标
+getWidth(): double 计算椭圆外接矩形宽
+getHeight(): double 计算椭圆外接矩形高
EllipseDrawerGUI
EllipseGraph
-ovalShape: Shape
GeneralizedEllipse -xCorner:double
-yCorner:double
New
-ellipGui: EllipseGraph -xLen:double
-ellipOper:EllipseOperations -yLen:double
-xCorner: double; New
-yCorner: double; +paintComponent():void
-xLen: double
-yLen: double
+initializeOvalByCorner(double xCorner, double yCorner,
double xLen, double yLen) Ellipse2D.Double
+initializeOvalByCenter(double xCenter, double yCenter,
double xRadius, double yRadius)
+initializeOvalByRectangle(double xLeft, double xRight, EllipseOperations
double yBottom, double yTop) -xCorner: double
+drawOval(): EllipseGraph -yCorner: double
+getOvalArea(): double -xLen: double
+getOvalPerimeter():double -yLen: double
+getEccentricity (): double -a: double New
+getFocalPoints(): Point2D[] 门面类 -b: double
-e: double
+getCornerX(): double
+getCornerY(): double +getOvalArea(): double
+getWidth(): double +getOvalPerimeter(): double
+getHeight(): double +getEccentricity ():double
+getFocalPoints(): Point2D[ ]

Design of ellipse application using Façade pattern


学生信息文档系统的例子

【例4】 学生信息文档,数据结构比较复杂。 现在
我们有一些学生信息文档类:
– StudentBasicInfo,
– StudentBasicInfoModel,
– AcademicRecord,
– StudentAcademicModel,
– Award, 和
– StudentAwardModel。
学生信息文档系统的例子

• StudentBasicInfo:负责从一个记录学生基本信
息的学生文档中读出学生的基本信息,
• StudentBasicInfoModel: 规定了学生基本信息的
格式。
• StudentBasicInfo: 当从文档中读出学生基本信
息的时候,其返回数据类型为
ArrayList<StudentBasicInfoModel>
类型。
• 因此,在类StudentBasicInfo中,需要调用类
StudentBasicInfoModel。
学生信息文档系统的例子

• AcademicRecord负责从另外一个文档中,读出
学生的学习科目与成绩信息。
• StudentAcademicModel: 规定了学生成绩信
息的格式。
• AcademicRecord: 从文档中读出学生基本信
息的时候,其返回数据类型为
ArrayList< StudentAcademicModel>
• 因此在类AcademicRecord中,要调用类
StudentAcademicModel。
学生信息文档系统的例子

• Award: 负责读出关于学生获奖的信息,
• StudentAwardModel: 规定了学生获奖的信息的
格式
• 在类Award中, 读取学生获奖的信息的时候,返回
数据的类型为
ArrayList<StudentAwardModel>
类型。
• 因此,在类Award中,调用了类
StudentAwardModel
学生信息文档系统的例子

• 以上的学生信息的返回类型,不是很好理解的,
例如ArrayList<StudentAwardModel>类型中的
ArrayList可以理解为长度可以弹性增长的数组,
而数组的每一项都是StudentAwardModel的数
据结构。
• 那么怎样才能在StudentAwardModel数据结构
中取出我们所需要的String类型的代表学生获奖
信息的数据结构呢?
学生信息文档系统的例子

• 为了得到String类型的学生获奖信息的各个分量,
可以使用该类中的为了从StudentAwardModel
类中分解出各种信息的方法getStudFirstName(),
getStudLastName(),getStudSerialNum(),
getAwardName(), getAwardDate()。
• 另外要注意的是各个类的接口是不一致的,例如
在StudentBasicInfo类的构造方法中,需要学生
姓名(name)、生日(birthdate)、学生号
(studentSerialNum);而在AcademicRecord的
构造方法中,需要学生的名(firstName)、姓
(lastName)、学生号(studentSerialNum)。
学生信息文档系统的例子

• 我们的目的是写一个客户类,该类负责抽取我们
所需要的学生的关于学生基本信息,学生课程信
息与学生获奖情况。对于以上的类的相对复杂的
数据类型,年轻的新手软件开发者可能要浪费很
多的时间写这样一个客户类。
• 因此我们可以找一个高级程序员,负责写一个门
面类StudentInfoFacade,提供以上的获取学生
总体信息的功能。设计类图如下。
学生信息文档系统的例子
ClientGUI

StudentInfoFacade StudentBasicInfo
- firstName: String;
- lastName: String;
- studNum: String; StudentBasicInfoModel
+extractStudentInfo(): String
+extractAcademicRecord(): String
+extractAllAwards(): String
+getStudentInfo(): String AcademicRecord

StudentAcademicModel
Award

StudentAwardModel
学生信息文档系统应用
门面模式的设计类图
学生信息文档系统的例子
StudentBasicInfo
- name: String;
- birthDate: String;
- serialNum: String;
+isExistingStudentName(String name)
+getStudentBasicInfo(): ArrayList

StudentBasicInfoModel
- name: String;
- birthDate: String;
-+getAllAwards(String
serialNumber: String; file): ArrayList
- ssNumber: String;
- major: String;
- degree: String;
+getName(): String
+getBirthDate(): String
+getSerialNum(): String
+getSocialSecurityNum(): String
+getMajor(): String
+getDegree(): String
学生信息文档系统的例子
AcademicRecord
- firstName: String;
- lastName: String;
- studNum: String;
+getAllScores(String file): ArrayList

StudentAcademicModel
- studFirstName: String;
- studLastName: String;
- studSerialNum: String;
- courseTitle: String;
- courseNum: String;
- score: String;
+getStudFirstName(): String
+getStudLastName(): String
+getStudSerialNum(): String
+getCourseTitle(): String
+getCourseNum(): String
+getScore(): String
学生信息文档系统的例子
Award
-+getAllAwards(String
firstName: String; file): ArrayList
- lastName: String;
- studNum: String;
+getAllAwards(String file): ArrayList

StudentAwardModel
- studFirstName: String;
- studLastName: String;
- studSerialNum: String;
- awardName: String;
- awardDate: String
+getStudFirstName(): String
+getStudLastName(): String
+getStudSerialNum(): String
+getAwardName(): String
+getAwardDate(): String
学生信息文档系统的例子

• 客户程序工作原理
• 客户程序直接调用StudentInfoFacade类中
的方法
– extractStudentInfo(): String
– extractAcademicRecord(): String
– extractAllAwards(): String
– getStudentInfo(): String
即可得到字符串类型的学生信息了。
用户图形界面 Back
门面模式和适配器模式的比较
Comparison of façade pattern and adapter pattern

何时使用对象适配器模式?何时使用门面模式?
1. An Adapter is used when the wrapper must
respect a particular interface and must
support a polymorphic behavior (当wrapper
接口必须支持多态性质的时候,可以使用对象
适配器模式).
2. On the other hand, a facade is used when
one wants an easier or simpler interface to
work with(当你需要一个容易使用的、简单的
门面类的时候,使用门面模式).
<<interface>>
Target
+f1():void
+f2():void
+f3():void Class1 Class2 Class3 Class4
+f4():void +f1():void +f2():void +f3():void +f4():void
+f5():void
+f6():void
implement

Adapter1 Adapter2
+f1():void +f1():void
+f2():void +f2():void 对象适配器模式
+f3():void +f3():void
+f4():void +f4():void 具有多态性质:
+f5():void +f5():void Target接口有两个
+f6():void +f6():void
实现类
Facade
+function1():void
+function2():void
+function3():void
+function4():void

Class1 Class2 Class3 Class4


+f1():void +f2():void +f3():void +f4():void

使用门面模式简单地产生一个门面类
几个例子的比较
几个例子的比较
• 例1:家庭安全系统。是针对一个已经存在的专门
用于家庭安全系统的类库写了一个门面类,在此
门面类中,设计了比较简单并且是常用的家庭安
全系统的功能。值得注意到是,这些新的功能的
实现,并不是简单的从类库中“抽取”的功能,
而是经过调用的方式,“组织”类库的若干功能,
从而形成了为一个新的功能。

• 例2:信息验证系统。与例子1类似。
几个例子的比较
• 例3:椭圆问题。是从设计一个数学工作者易于使用的椭圆
类的目的出发,列出数学家所需要的所有的功能,然后试
图找到能支持实现这些功能的类库,即首先有强烈的目的,
再试图在Java API的大范围的类中寻找可以支持实现这些
功能的类。幸好,在Java API中确实存在例如
Ellipse2D.double的类与Paint类可以调用,以便组成数学家
需要的功能。一个功能,比如计算离心率等,需要经过计
算得到。例子2.5是调用本来互不相干的类
(Ellipse2D.double的类与Paint类)的一些功能,形成了新
的功能。
• 例4:学生信息抽取系统。学生信息文档中所涉及的类库中
的类的数据类型是比较复杂的,因此,如果不使用门面模
式,一个一般的程序员不太容易使用该类库。因此,写了
一个门面类StudentInfoFacade。这样,通过使用该门面类,
使得系统更加容易使用。

Back
Software Architectures
DB DB DB

file1 file2

End Client Server Shared


user software software resources

Back
(mainframe, -1970’s):

• From 1960’s to 1970’s, mainframe computer


applications were popular, regarded as one tire
client/sever application.
• There are two ways for the mainframe to work

Øa number of card punch would be used by


programmers to write their programs "offline". Then
Øthe “program” in the punched card were submitted to
the operations team, who would schedule them for
running.
Prog 5 Prog 4 Prog 3 Prog 2 Prog 1

Magnetic tapes with recorded program

Main frame computer


Prog 1

Prog 2

Prog 3

Prog 4

Main frame computer


• As time passed, computer prices were
lower and lower, corporations separated
mainframe-based applications into
– Client and
– Server
components
2. Evolution of client-server architecture

Client LAN file

File
file
server
Client
File calls file

Client files
2. Evolution of client-server architecture

Sun, Mike 356821 TV 888.56


Lee, Mary 842674 radio 65.44
Juell, Paul 257215 Telephone 97.05
Nygard, Ken 573245 Microwave oven 56.88
Magel, Ken 834265 refrigerator 988
Hunt, Paul 332184 Bicycle 523
Eric, Vosika 257652 Watch 1005
2. Evolution of client-server architecture

Liu, feng 221231 camera 506.00


Sun, Mike 356821 TV 888.56
Lee, Mary 842674 radio 65.44
Juell, Paul 257215 Telephone 97.05
Nygard, Ken 573245 Microwave oven 56.88
Magel, Ken 834265 refrigerator 988
Hunt, Paul 332184 Bicycle 523
Eric, Vosika 257652 Watch 1005
2. Evolution of client-server architecture
2. Evolution of client-server architecture

GUI & Applications, DBMS, Legacy & other


Part of business logics SQL calls Resource Managers,
Program for accessing Part of business logics
DB

Database
SQL Server
Calls (DBMS)
SQL SQL
SQL

tier 1 tier 2

2-Tier Client/Server: Databases replaced File Server


2. Evolution of client-server architecture

: GUI + Business Logic,


: Database + Shared Resources +
Business Logic (少量的程序)

• 2-Tier is simple
• Small departmental decision support
• Simple Web publishing applications
2. Evolution of client-server architecture

• Application or business logic either resides on the


client or on the database server in the form of
stored procedures (存储过程)
• More complex applications
= fatter clients
= more expensive PC’s for each user
• Database applications developed by Power
Builder and VB have 2-tire client-server structure:
front end + database
2. Evolution of client-server architecture

• 两层客户端-服务器架构的优点: 与文件共
享系统相比,因为两层客户端-服务器发送
请求与回答而不是文件,从而降低了网络
使用。
2. Evolution of client-server architecture
• 两层客户端-服务器架构的缺点:
Ø 它是单一服务器且以局域网为中心的,所以难以扩展
至大型企业广域网或 Intranet;
Ø 数据库厂商的lock-in, 因为你的GUI代码直接与DB
服务器绑定。更换其它产品困难;
Ø 配置问题:当配置到远程的环境时候,两层的C/S结
构管理起来比较困难。尤其是对于胖客户端的情况,
就更难管理;
Ø 胖客户端导致程序维护困难:用户必须在客户端安装
特定的客户端应用程序,而且当越来越多的企业的业
务逻辑写在客户端应用程序中的时候,程序维护变得
越来越困难。
Ø 软件升级困难:需要每个客户端都要安装新的客户端
应用程序
2. Evolution of client-server architecture
2. Evolution of client-server architecture
Database, DBMS,
Application
Services Legacy & other
GUI 请求 Business SQL Resource Managers
Browser logic

RPC Application SQL


Database
ORB Server Data
Server
MOM Access
(DBMS)
HTTP

tier 1 tier 2 tier 3


DB access
Run GUI
program

客户端 应用层 数据层


3 tire client/Server Architecture
2. Evolution of client-server architecture

• 3-tire client/server architecture is the most popular


architecture
• All other multiple client/server architecture are
derived from the 3-tire client/server architecture
• The application layer in the 3-tire client/server
design can be divided into several layers.
2. Evolution of client-server architecture
Client Tier GUI PC

Business Application
Logic tire Server

DB & DB Server
DBMS
A special 3-tire client/server program Back
Advantages (over 2 tire client server architecture):
1.三层客户端-服务器架构更容易维护。Application logic
becomes separated from the GUI and the database;
Changes in one tier should not affect the other tiers
2.三层客户端-服务器架构可以有瘦客户端。
Ø Web applications: all business logics are in the server,
and the server is also responsible for generating web
client, and so in the client machine, what is needed is
windows operating system with browser. Using the
browser, the web pages can be downloaded from the
server to the client (the client tire is very thin).
ØClient application: some client side software are
deployed on the client machine (网络游戏、电子商务)
三客户端-服务器架构中,

三层客户端-服务器架构
2-Tier 3-Tier
System Complex. Less Complex
Admin. more logic • the application can be centrally managed
on the client on the server –
to manage • application programs are made visible to
standard system management tools

Security Low High


data-level fine-tuned at the service, method, or object
security type level
Low. High.
data representation client invokes services or
exported methods
Excellent.
Poor. Excellent.

Hetero No. Yes.


database
support

Back
三层架构与三层客户端-服务器软件体系结构的区别

Ø 三层架构(包括显示层,应用层与永久数据保持层
)中的层指的是逻辑意义上的层。这些层,可以部
署在同一台计算机上,当然也可以部署在不同的计
算机上。
Ø 三层客户端-服务器架构里面所涉及的层指的是物理
意义上的层。
Ø客户端运行在PC上;
Ø应用层被部署与运行在应用服务器上;
Ø数据层包含数据库与数据库管理系统软件,被部
署与运行在数据库服务器上。
三层架构与三层客户端-服务器软件体系结构的区别

Presentation Client PC
Layer

Application
Layer Application Server 服务器

Permanent Data
Storage Layer Database Server
服务器
(DBMS)

Database
三层架构与三层客户端-服务器架构
Browser/
三层客户端- Beans/
ActiveX
服务器架构

Application
Services
Business logic

Databse, DBMS,
Legacy & other
Resource Managers
Browser/
三层客户端- Beans/
ActiveX
服务器架构

Presentation Layer

Business logic Layer

DB Access Layer

Database, DBMS,
Legacy & other
Resource Managers
三层架构与三层客户端-服务器软件体系结构的区别

• 例子:
• 假如我们要利用三层客户端-服务器架构设
计一个运行于Web上的简单的网上运动会
管理系统。则我们可能将软件系统设计为
如下图所示的系统。
2. Evolution of client-server architecture
Client Tier GUI PC

Presentation Layer
运动会 Application
Business logic Layer 业务逻 Server

DB Access Layer

数据库与 DB Server
DBMS
An example design of a 3-tire client/server program
2. Evolution of client-server architecture

• 注意到,在本设计中,对于三层的客户端-服务器架
构的应用层部分,设计为一个通常意义下的三层的层
次架构。
• 该架构包含显示层,用于生成用户图形界面,具体地
说,图形界面生成代码被部署在服务层,但是生成的
界面被显示在客户端PC上。
• 应用层包含所有的业务逻辑核心代码,永久数据保持
层包含所有的数据库访问代码,例如JDBC代码。
• 实际上,层次架构里面的所谓的三个层都被部署在应
用服务器上。因此,本设计可以被认为是应用了三层
的客户端-服务器架构,其中在应用层中,包含了通
常意义下的一个三层架构的程序。
2. Evolution of client-server architecture

• 不要以为所有的程序都允许在互联网上
• 在现实的软件开发中,除了运行在互联网上的
程序外,还有很多程序不运行在互联网上,例

ØMatlab软件,就是运行在桌面的软件;
Matlab提供了强大的计算、仿真、绘图等功
能因此,通常意义下的层次架构也具有广泛
的用途
Ø智能无人机控制软件
Ø制造业软件
Client Tire
Web Client
运行在 Application Application running in
客户机 Client Client
Container
Web Browser,

Web Tire
Java Bean Web Pages
Web Components
Container (optional)
Servlets
运行在
JavaEE
服务器 Business tire
J a v a Message Driven
EJB persistence Beans
Container Entities
Session Beans

运行在
数据库 EIS Tire Database and
服务器 Legacy system
: scalable,
flexible, clear separation of application areas,
network efficient; expensive, difficult to implement
: convenient for small user
base, easy to implement; not very scalable, db
vendor lock-in, not very flexible
• JavaEE architecture: a special kind of 3-tire
client server architecture, is the most suitable
architecture for developing high quality web
applications
Question for Students

• Question: What is the main difference between


a 3-layer layered architecture and a 3-tire
client/server architecture?
• Incomplete Answer:
– A 3-layer layered architecture organizes the program
into logical layers, all the layers can run in one
computer
– A 3-tire client/server architecture also design the
program into layered fashion: client tire runs on the
client machine, business logic layer runs on the
application server and DB and DBMS runs on the DB
server

Back
Professor:
Yushan (Michael) Sun
Fall 2016
Contents of this lecture

1. Introduction to the strategy pattern


through Design of a sorting program
Introduction to the strategy pattern through
Design of a sorting program

【例1】Design of a sorting program


Requirement: design a program to sort integers
by using
– Bubble Sort
– Heap Sort
– Insertion Sort
– Quick Sort
respectively.
Introduction to the strategy pattern through
Design of a sorting program

• Design 1: use a single class named sorting


to implement all the sorting algorithms

+main(String[ ] args )

+bubbleSort (int[ ] nums) : int[ ]


+heapSort (int[ ] nums) : int[ ]
+insertionSort (int[ ] nums) : int[ ]
+quickSort (int[ ] nums) : int[ ]
Introduction to the strategy pattern through
Design of a sorting program
The code may look like this
Public class Sorting {
public static void main(String[ ] args ) {
int choice;
if (choice ==1) { bubbleSort (nums); }
else if (choice ==2) { quickSort (nums); }
//…
}
public int[] bubbleSort (int[] nums) {// code}
public int[] heapSort (int[] nums) {// code}
public int[] insertionSort (int[] nums) {// code}
public int[] quickSort (int[] nums) {// code }
} //the code works, but it has some problems
• How to improve the design?
+main(String[ ] args ) +bubbleSort (int[ ] nums) : int[ ]
+heapSort (int[ ] nums) : int[ ]
+insertionSort (int[ ] nums) : int[ ]
+quickSort (int[ ] nums) : int[ ]
s.bubbleSort (nums);
bubbleSort (int[] nums) {//code }
heapSort (int[] nums) {//code }
insertionSort (int[] nums) {//code }
quickSort (int[] nums) {//code }
:
+main(String[ ] args )

+bubbleSort (int[ ] nums) : int[ ]


+heapSort (int[ ] nums) : int[ ]
+insertionSort (int[ ] nums) : int[ ]
+quickSort (int[ ] nums) : int[ ]
• How to improve the design further?
• Any better ideas?
Design 3. We further split the Sorting class into 4
classes to get the following design

Sorting
The advantages of this design

Sorting
Sorting
Dependency
inversion

Back
Something About Code for Sorting
Theory of the Strategy Pattern

Strategy
提供了一个
共同的接口

为调用准备环境

Diagram of Strategy pattern


Theory of the Strategy Pattern

• Strategy
– declares an interface common to all
supported algorithms.
– Context uses this interface to call the
algorithms defined by a ConcreteStrategy.
• ConcreteStrategy
– implements the algorithm using the Strategy
interface.
Theory of the Strategy Pattern

Context
Ø is configured with a ConcreteStrategy
object.
Ø maintains a reference to a Strategy object.
Ø may define an interface that lets Strategy
access its data.

-strategy: Strategy
Theory of the Strategy Pattern
When to use this pattern?
Use the Strategy pattern in any of the following
cases:

When many related classes differ only in their


behaviors. Strategies provide a way to configure a
class with one of many behaviors.

When an algorithm uses data that clients


shouldn't know about. Use the Strategy pattern to
avoid exposing complex, algorithm-specific data
structures.
Theory of the Strategy Pattern

When a class defines many behaviors, and


these appear as multiple conditional statements
in its operations. Instead of many conditionals,
move related conditional branches into their own
Strategy class.
Theory of the Strategy Pattern

A context may pass all data required by the algorithm


to the strategy when the algorithm is called. 调用时,
Context类将Strategy类所需要的所有数据一次性地传
递完毕

av.find(a)

a={12, 5, 21, 37, 8, 25}


Theory of the Strategy Pattern

A context may pass itself as an argument to Strategy


operations. That lets the strategy call back on the
context as required. Context将自己作为一个对象传递
给Strategy类,然后Strategy类再利用该对象反过来调
用Context类,以便获得某些数据与功能
f.apply(p, this)
Theory of the Strategy Pattern

, Clients usually create an object of


ConcreteStrategy and pass the object to the
context;

.
, clients interact with the context
exclusively.
Theory of the Strategy Pattern

Client Strategy stra = new ConcreteStrategyA();


Context con = new Context(Stra);
main() con.goWork();

goWork()

Context st.
+Context(Strategy st)
+goWork();

st.
Theory of the Strategy Pattern

策略模式的优点 Advantages of Strategy Pattern

. Hierarchies
of Strategyclasses define a family of
algorithms or behaviors for contexts to reuse.
– Inheritance can help factor out common
functionality of the algorithms.
Theory of the Strategy Pattern

2.
Encapsulating the algorithm in separate Strategy
classes lets you change the algorithm independently
of its context, making it easier to
• understand,
• switch (change to a more efficient algorithm)
• extend.
Theory of the Strategy Pattern

.
• A client must understand how Strategies differ
before it can select the appropriate one.

Back
【例2】Sorting Problem – New Design in the
Strategy Pattern with Context Class

• We need to design a sorting program using several


sorting algorithms to sort integer arrays。The
program includes
– 用户图形界面 Graphical User Interface:for user’s
input and output
–排序算法封装类 Classes to encapsulate the
sorting algorithms
– 计算每个算法的执行时间 Computation of the
execution time taken for each sorting algorithm。
The result will be shown on the screen
1.创建某个策略子类对象s
Main()
2. 创建Context对象,将s配置给Context

-sort: SortingAlgorithm
+Context(s: SortAlgorithm) 3. s.sort(a, c)
+sortIntArray(): int[]
+startExecution(): void
+endExecution(): void 4.利用c调用 +sort(a: int [ ], c: Context)
+getExeTime(): long Context的方法

+sort(a: int[], c:Context) +sort(a: int[], c:Context) +sort(a: int[], c:Context) +sort(a: int[], c:Context)
:Client Strategy s = new ();
Context con = new Context(s);
main() intArray = con.sortIntArray(intArray);

con.sortIntArray(intArray);
s.sort(a, this)
:Context
Context(Strategy st) startExecution()
sortIntArray(int[] a) endExecution()
+startExecution(): void
+endExecution(): void ct.startExecution()
+getExeTime(): long ct.endExecution

The typical interactions of the system


class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(SORT)) {
if (type.equals(BUBBLE))
sa = new BubbleSort(); 1. 用户创建策略子类对象
if (type.equals(HEAP)) sa
sa = new HeapSort(); 2. 将sa作为创建Context类
if (type.equals(INSERT)) 的对象的参数传递给
sa = new InsertSort(); Context
if (type.equals(QUICK)) 3. 在用户类中使用Context
对象调用
sa = new QuickSort();
sortIntArray(intArray)
getExeTime()方法
context = new Context(sa);
intArray = context.sortIntArray(intArray);
long eTime = context.getExeTime();
}}}
SortAlgorithm alg; 1. 策略子类对象alg
private long startTime; 由构造方法传入
private long endTime;
2. 在sortIntArray方
public Context(SortAlgorithm alg) { 法中,直接使用
this.alg = alg;
} alg调用策略类的
public int[] sortIntArray(int[] a) { sort方法
return this.alg.sort(a, this); 3. 同时,将Context
}
public void startExecution(){ 对象传递给策略类
startTime = System.currentTimeMillis(); 4. 策略类利用该
} Context对象调用
public void endExecution(){
endTime = System.currentTimeMillis(); 计算程序执行时间
} 的方法
public long getExeTime(){
long exeTime=0; startExecution()
exeTime = endTime-startTime; endExecution()
return exeTime;
}
}
public interface SortAlgorithm {
int[] sort(int[] nums, Context ct);
}
public class BubbleSort implements SortAlgorithm {
public int[] sort(int[] intArray, Context ct){
ct.startExecution();
for(int i = intArray.length; --i >= 0;)
for(int j = 0; j < i; j++){
if(intArray[j] > intArray[j + 1]){
int T = intArray[j];
intArray[j] = intArray[j + 1];
intArray[j + 1] = T;
}
}
ct.endExecution();
return intArray;
}
}
public class InsertSort implements SortAlgorithm {
public int[] sort(int[] intArray, Context ct){
ct.startExecution();
for (int i = 1; i < intArray.length; i++){
int j = i;
int numToBeInserted = intArray[i];
while ((j > 0) && (intArray[j-1] > numToBeInserted) ) {
intArray[j] = intArray[j-1];
j--;
}
intArray[j] = numToBeInserted;
}
ct.endExecution();
return intArray;
}
}
【例3】十二属相(Chinese Zodiac)介绍:我们要设计一个
介绍中国十二属相的程序。我们试图使用策略模式对以上问
题进行设计。
• 首先,我们将十二属相各自封装为一个类。并且为这些
类设计一个共同的接口ChineseZodiac。
• 用户使用用户图形界面输入自己的出生年月日,并且在
创建Context对象的时候,将日期作为参数传递给
Context类。
• Context类根据用户输入进行计算,得出应该初始的属
相类,并且负责创建该属相类对象。Context类使用该
对象调用该子类的say()功能,介绍该属性的特点。
• 设计类图如下。
ClientGUI

Context
-zodiac:ChineseZodiac zodiac
+Context(y:String,m:String, d: String)
+parseZodiac()
+setupZodiacToYear() <<interface>>
+createZodiacObj() ChineseZodiac
+getZodiacDescription()
+say()

Rat Ox Tiger Rabbit


+say() +say() +say() +say()

利用策略模式设计的十二生肖特点介绍类图(有省略)
ClientGUI Context con = new Context(y,m,d);
con. getZodiacDescription()

Context
-zodiac:ChineseZodiac
+Context(y, m, d) zodiac
+parseZodiac()
+setupZodiacToYear() <<interface>>
+createZodiacObj() 创建Tiger对象tg ChineseZodiac
+getZodiacDescription() +say()
tg.say()

Rat Ox Tiger Rabbit


+say() +say() +say() +say()
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(FIND)) {
String yr = getYear();
String mon = getMonth() ; 这里没有将具体的策略子
String date = getDate(); 类的对象传递给Context类
Context context = new Context(yr, mon, date );
String saying = context.getZodiacDescription();
ImageIcon icon = context.getImageIcon();
setImageInfo(icon);
txtDisplayZodiac.setText("");
showZodiacInfo(saying);
}
} }
class Context {
ChineseZodiac zodiac; String yr; String mon = null; String date = null;
String[] z = {"rat", "ox", "tiger", "rabbit", "dragon", "snake", "horse",
"sheep", "monkey", "rooster", "dog", "pig"};
String[] yz = new String[2200];
boolean flag = false;
public Context(String yr, String mon, String date) {
year = yr;
month = mon;
this.date = date;
createZodiacObj();
}
public String getZodiacDescription() {
return zodiac.say();
}
public ImageIcon getImageIcon(){
return zodiac.setImgIcon();
}
public ChineseZodiac createZodiacObj(){
return zodiac; //根据用户输入,计算并返回相应的对象
}
}
策略层次类接口代码如下。
public interface ChineseZodiac {
abstract public String say();
abstract public ImageIcon setImgIcon();
}
策略层次类具体的子类代码如下(省略了其它生肖)。
public class Rat implements ChineseZodiac {
public String say(){
String description = “You have a zodiac Rat.”;
return description;
//省略了一些代码。
}
public ImageIcon setImgIcon(){
ImageIcon imgIcon = new ImageIcon("images/rat.jpg");
return imgIcon;
}
}
本例子中Context类的设计说明:
• 由于属相的个数(12个)不会再增加了,而只存
在我们对每个属相的诠释有可能改变。
• 因此我们让Context类负责创建属相类的对象(会
有许多关于初始化属相类的条件语句)。
• 假如我们再新增加一个新属相类(虽然这是不可
能的),例如“大象”属相的策略子类,则
context类需要修改;但是,如果我们要修改关于
某个属相的性格与命运的描述,则不需要修改
context类的任何代码。
本设计的优点:
1) 在添加或者修改属相子类的情况下都不必修改客
户类的代码,
a) 这是因为客户类仅仅提供一个人的生日信息,而不包
含关于属相子类的条件语句。创建属相类对象的责任
放到了Context类里面,
b) 因此,Context子类包含一些与属相相关的条件语句。
但是考虑到本问题不可能在增加子类方面进行扩展,
因此不存在增加策略子类的情况;
2) 在修改某个属相子类的情况下,不需要修改
Context类的代码;
3) 添加一个属相子类或者修改某个属相子类不影响
其它的属相子类。
本设计的缺点
本设计从表面上看,缺点是可扩展性没有采
取例2的设计好(例如增加新的属性,猫)
【例4】 相同的数据的不同的图表显示的例子。在
政府或者商业网站上,有许多数据需要利用图表解
释,用户往往可以选择不同的图表以便方便地显示
一些数据,例如显示全国各个行业的外贸出口比例
等等。对于一组相同的数据,可以有不同的图表显
示:
– 条形图(Bar),
– 折线图(Line),
– 饼图(Pie),
– XY散点图(XY (scatter)),
– 面积图(area)
等等图形。
为什么要使用策略模式进行设计?
• 我们假设在用户在输入一组数据以后,程序将为你
根据需要画出你所需要的图表类型。
• 由于所有的图表,虽然表现形式不同,都被用来显
示同一组数据,所以,功能是相同的。有鉴于此,
我们可以使用策略模式实现各种图表的显示。
• 根据策略模式,我们可以将该根据用户输入的一组
数据,利用各种不同的图标显示。为简单起见,我
们在本例子中,只使用
–条形图(Bar),和
–饼图(Pie)。
程序设计类图如下。
ChartDrawerGUI

<<interface>>
ChartGraph
paintComponent(Graphics g)
JPanel JPanel

BarChartGraph PieChartGraph
BarChartGraph(double[] height) BarChartGraph(double[] height)
paintComponent(Graphics g) paintComponent(Graphics g)

使用策略模式设计的绘图软件-省略Context类的情况
程序设计类图如下。 根据用户提供的数据与选择,创建,例如
ChartGraph p= new PieChartGraph(data)
ChartDrawerGUI

<<interface>> 根据
ChartGraph
Data
paintComponent(Graphics g) 画出图
JPanel JPanel

BarChartGraph PieChartGraph
BarChartGraph(double[] height) BarChartGraph(double[] height)
paintComponent(Graphics g) paintComponent(Graphics g)

使用策略模式设计的绘图软件-交互情况
用户图形界面-当用户选取了Barchart的情况
用户图形界面-当用户选取了Piechart的情况
为什么在本设计中省略了Context类?
• 原因是在本类图的两个具体的策略实现类BarChartGraph和
PieChartGraph中,都有一个paintComponent(Graphics g)方
法,实际上,在该方法中,调用其超类JPanel的Protected方
法paintComponent(Graphics g)。
• 在生成BarChartGraph或者PieChartGraph的对象的时候,
paintComponent(Graphics g)方法将自动运行。也就是说,
BarChartGraph或者PieChartGraph的对象代表一个JPanel,
并且相应的条形图(Bar chart)或者饼图(Pie chart)图表已经被
绘制在该JPanel上。
• 因此,为了我们将图形信息显示在用户图形界面上的目的,
我们只要创建BarChartGraph或者PieChartGraph的对象并且
将其显示在图形界面上就可以了。所以我们省略了context类。
以下我们要给出程序的源代码。
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e)
if (e.getActionCommand().equals(DRAW)){
String chart = getSelectedChart();
double[] data = getInputData();

if(isValidData == true){
if(chart.equals(BARCHART))
chartPanel = new BarChartGraph(data);
else if(chart.equals(PIECHART))
chartPanel = new PieChartGraph(data);

//下面语句直接调用了策略子类的Paint()方法
graphPanel = (JPanel)chartPanel;
}
}}
public class BarChartGraph extends JPanel
implements ChartGraph{
private Shape rectangle[];
private double[] height;
private int inputLen;
public BarChartGraph(double[] height){
this.height = height;
setBackground(Color.pink);
inputLen = height.length;
rectangle = new Shape[inputLen];
}
public void paintComponent(Graphics g){
super.paintComponent(g);
以下代码绘制条形图
}
}
public class PieChartGraph extends JPanel implements ChartGraph{
private double[] slices;
private Shape arcs[];
private double total = 0.0D;
private int inputLen;
final static double X = 100.0D;
final static double Y = 20.0D;
final static double W = 100.0D;
final static double H = 100.0D;
public PieChartGraph(double[] slices){
this.slices = slices;
inputLen = slices.length;
arcs = new Shape[inputLen];
setBackground(Color.pink);
}
public void paintComponent(Graphics g){
//饼形图代码
}
} Back
策略模式的可扩展与可维护性讨论

情况1:客户类负责创建策略子类的对象的情况。
l 客户类根据用户提供的不同的请求,负责创建不同的策
略子类的对象,然后再将该对象传递给Context类。此
时若context类为任何的不同的策略子类的同名方法都
提供了相同的参数,则在context类中不必使用任何与
策略有关的条件语句。
l 在这种情况下,修改或者添加一个策略子类都不必修改
context类。但是,在添加一个新的策略子类的情况下,
如果客户类需要使用该子类的情况下,需要在客户类中
添加一个新的条件语句。也就是,客户类需要修改。例
如例2与例4的设计。其中,例4省略了Context类。
l 该设计符合开闭原则
策略模式的可扩展与可维护性讨论

情况2. Context类负责创建策略子类的对象的情况。
• 将创建策略子类的对象的责任交给context类,而客
户类client只提供给context类一些代表客户请求的
参数。
• 在此情况下,context类在创建策略子类的对象的时
候,往往会使用与策略子类有关的条件语句。此时,
– 修改一个策略子类不需要修改context类。
– 而在添加一个新的策略子类的时候,则必须在
context类中添加新的条件分支,也就是说,需要
修改context类。例如,例3的设计。
• 综上所述,还是由客户类创建对象的设计可扩展性
好一些。这样,可以做到在context类中不出现与策
略子类相关的条件语句,从而,可扩展性也得到了
提高。
1. Introduction to P2P

6. Data Transfer Mechanism from Node to Node


7. JXTA-P2P Protocol
1. Introduction to P2P

Problems with traditional C-S architecture

:
1. Introduction to P2P

• Shawn Fanning was a student at North Eastern


University in Boston in 1998
• He was sitting in his dorm room talking with
friends, complaining about dead MP3 links.
1. Introduction to P2P

• Shawn Fanning´s American dream:


• To establish a company called Napster to
access and use the resources on the
distributed hard drives in our computers
effectively.
1. Introduction to P2P

Actions:
• Shawn Quits university to develop Napster
idea.
• He codes his program working 16 hours a day.
• Shawn Finishes the program in summer 1999 at
age 19.
• Huge success, putting Fanning on the cover of
magazines and newspapers.
1. Introduction to P2P

• Napster Corp was founded in Sep 1999 by


• Shawn Fanning (19 years old) and
• Sean Parker (20 years old)
based in San Mateo, California with
• 15 million dollars
• Napster became one of the 50 most visited
pages in the world.
1. Introduction to P2P

P2P Client/Server

Difference between P2P and client-server


1. Introduction to P2P

What is Peer-to-Peer (P2P)?


Peer-to-Peer computing is described as the sharing
of and services by direct
exchange between systems.

a) information,
b) processing cycles,
c) cache storage, and
d) disk storage for files.
1. Introduction to P2P

Return
目录服
务器

One Example
Sorted list of
closest clients
with Latest
version content
Node3 …
Node5…
Node8…
Node12…
Node15 …
Once peers are located, they can provide
information about their
Øcapabilities (e.g., memory

Øthe services they provide (


).
• After it determines their locations, the peer then
attempts to establish contact with all of the
buddies that it has found.
interface for
contacts
• The user interface provides information to
the user about what other users are on-line.
Return
Pure P2P architecture
a) 节点既是客户端又是服务器 Peers can act as
clients and servers and have the same
capability as its neighbors.
b) 没有中心服务器 It has no central servers. It
has every node as a Peer and has no central
router.
c) There are two routing structures,
1. 分布式目录 One is a

2. 直接发送消息 The other .


Find

Process of sending a query message


Find

Process of sending a query message


• Gnutella, a Pure P2P Model, is a
application and protocol:
– the end hosts join Gnutella by connecting to
existing end hosts already on the Gnutella.
Gnutella History
Justin Frankel
• Originally conceived of by Justin Frankel, then
21 year old, founder of Nullsoft
• Nullsoft posts Gnutella to the web on 2000/03,
• Nullsoft was later acquired by AOL, which has
now stopped this project.
• However, the Gnutella application had already
distributed as an open source application (with
different versions).
• Gnutella has become a Protocol now.
1. 【Connect to P2P Network】Node A is first
connected to the network.
2. 【Find New Nodes] Ping Node A Pings to the
other Nodes (B and C) to discover new
nodes on the network.
3. 【New Node Replies】Pong A pong message
is sent as a reply to a ping and provides
information on a network node, including
address,
Ø port number (端口号), and
Ø number of files shared.
A
is used to search for files shared by
other nodes on the network. It contains a
query string and a minimum requested link
speed.
1)发送给7个附近的client(第1层)
2) 每个第1层节点再发送给6个附近的节点(第2层)
3)每个第2层节点再发送给5个附近的节点(第3层)
。。。

没找到

Search is not guaranteed if object is outside the search range!


1) Unstable connectivity of the servants
– performance management difficult
2) Scalability issues: e.g. when TTL=10,
will produce huge networks
3)搜索范围不够大,本应该存在的资源没有
被覆盖
Gnutella
• Gnutella is a such that the
and
at the same time. A node
– is a when it is looking for some data and
– is a if it is servicing a request of another
node.
:If one computer goes down, the network
is unaffected, .
b) Gnutella permits of any type.
c) Anonymous:Gnutella is anonymous-there is no
need to provide a name or e-mail address to use
Gnutella
d) Share anything:Gnutella
can share anything,
family photos, computer program, and home
movies, etc.
e) Pure P2P: Gnutella is Pure P2P and is completely
decentralized.
Return
• Problems in traditional pure P2P architecture
Gnutella V0.4
• 网络搜索量大增。Large scale P2P networks
around the world caused the ever-increasing
search traffic across different administrative
domains.
• 对于大的网络,搜索应答率比的越来越低。The
search recall ratio ( the number of search
results:the total number of available copies
of the searched object) was significantly
decreased as the network scale became
larger
• 需要新设计,以便改善性能
• To tackle this problem, Gnutella v0.6
introduced two-layer hierarchy in its
architecture as below
leaf leaf leaf leaf
超级节 leaf leaf
leaf
点sn Sn1 Sn2

叶子节 Sn3 Sn4 Sn5 Sn6


点leaf
Sn7
leaf Sn8
leaf
leaf
leaf leaf leaf leaf

Gnutella v0.6 network topology


• Explaination of the architecture
• In this architecture, nodes are divided into
into leaf nodes and ultrapeer nodes.
• A leaf node(叶子节点) : only maintains
connection with its own ultrapeer,
• An ultrapeer(超级节点):
– maintains connections to its own leaf
nodes and acts as proxy for them
– connects to the other ultrapeers from the
overlay
• One ultrapeer can connect with multiple leaf
nodes, depending on its capacity and capability.

• 在查找过程中,叶子节点的责任. Leaf nodes are


only responsible for
– initiating lookup requests,
– receiving correlated lookup response, and
– responding the requests that they can exactly
answer,
• 在查找过程中,超级节点的责任。
• Ultrapeers are responsible for
–转发请求到其它超级节点 forwarding lookup
requests to other ultrapeers or
–转发请求到自己的叶子节点 its own connected
leaf nodes, if it knows exactly the leaf node is
able to answer the request.
• Ultrapeers can also initiate requests and
receive correlated responses.
• At the level of ultrapeer, similar flooding-
based mechanism as Gnutella v0.4 is utilized
to forward the lookup requests.
leaf leaf leaf leaf
leaf leaf
leaf
Sn1 Sn2

Sn3 Sn4 Sn5 Sn6

Sn7
leaf Sn8
leaf
leaf
leaf leaf leaf leaf 找到了

查找过程示意图 Return
每个节点都应该安装相同的软件
Each peer provides a
1. 负责通讯 Handles communication with
the network,
2. 管理信息 Manages information about the
location, status, and privileges.
3. 提供扩展模块基础 Provides the foundation
for extension modules
节点软件的架构
The architecture of a Peer implements the layered
architectural Pattern. The functions are layered one
on top of the other.
Layer 1. web server
Layer 2. Servlet engine
Layer 3. The request manager
Layer 4. The event service
Layer 5. Buddy manager
Layer 6. Access control
Web agent
Extension

(html)
chart
modules

Core
Outgoing
components
events sent
via HTTP

Web Server
foundation

Incoming Incoming
events from HTTP servlet
HTTP requests

the architecture of an individual peer


• Event Service
Receive that are passed over HTTP. The
events carry the bulk of communication
between peers.

Event service
Øreceive the events
Øinvoke the services that have registered interest
in those events
Øallow components to send events to other peers
is a means of
Øidentifying individual users and
Øcontrolling the access relationships between
peers: who may access resources and about
whom the user would like information
ØInformation in the incoming event or HTTP
request serves to identify users as being
welcome or not
ØIt also defined levels of access, thus the
user may permit or deny access to
services.
• Dynamically loaded extension that
provide new functionality for specific
applications the peer’s core
functionality.
Ø Allow custom configuration of peers, in most
cases even while the peer is running.
Ø May be mapped to handle incoming HTTP requests,
register for events, send events to other peers, etc.
Ø Can communicate in a controlled fashion with
other modules within the same peer
Return
The processing steps act as filters, which
manages the passing of data between two
nodes.

– When a peer requests for a file, a filter


component effectively filters the
which do not match the search criteria
and produces a result in the form of a list to
the query.

– Then when the user chooses to download, it uses a


pipe to transfer the data from the host (用管道下载)

Return
JXTA Java™ Standard Edition v2.5:
Programmers Guide
• JXTA™ is a set of open, generalized peer-to-peer
(P2P) protocols that allow any networked device
– sensors,
– Cell phones,
– PDAs,
– laptops,
– workstations,
– servers and
– supercomputers
to communicate and collaborate mutually as peers.
JXTA™ Architecture

• The JXTA software architecture is divided into


three layers, as shown in Figure 2.
Sun Jxta Third Party
Jxta Shell 应用层
Applications Applications

服务层

JXTA
核心层

Return
Professor:
Yushan (Michael) Sun
Fall 2016
Contents of this lecture

1. Example of State Related System


2. The State Design Pattern
Example of State Related System
【例1】Silkworm example

hatch
Egg

eat
walk shedSkins
mate changeColor
Moth layEggs Worm spinCocoon
die produceSilk
changForm

Pupa
makeHole
goOut
changeForm
Silkworm
-state: String
-EGG_STATE: String How do you think
-LARVA_STATE: String
-PUPA_STATE: String about this design?
-MOTH_STATE: String
-species: String
+hatch(): void
+eat(): void Drawbacks of the design:
+shedSkins(): void
+changeColor(): void 1) The methods here are
+spinCocoon(): void really state specific
+produceSilk():void 2) A client class doesn’t
+changForm(): void
+makeHole(): void know in what state,
+goOut():void what method can be
+changeForm(): void called
+walk(): void
+mate(): void
+layEggs(): void
+die(): void
Silkworm
-state: String
New Design -EGG_STATE: String Advantages:
-LARVA_STATE: String
-PUPA_STATE: String Now the client
-MOTH_STATE: String program knows
-species: String in what state,
what methods
+changeState(): void
can be called

Egg Worm Pupa Moth


+hatch(): void +eat(): void +changeForm(): void +walk(): void
+changeState() +shedSkins(): void +makeHole(): void +mate(): void
+changeColor(): void +goOut():void +layEggs(): void
+spinCocoon(): void +changeState(): +die(): void
+produceSilk():void +changeState()
+changForm(): void
+changeState():
【例2】Monkey example.
A monkey is really a moody animal. Suppose that
a monkey has 3 states (moods):
– Happy:dance;
– Mad:make noises
– Angry:scream
First design:use a single class to encapsulate
behaviors

Monkey
-state: String Public void behave(){
if( state.equals(“happy”) )
+dance (): void
monkey. dance();
+makeNoises: void
else if(state.equals(“sad”) )
+scream ():void monkey. makeNoises();
+behave(): void else if(state.equals(“angry”) )
+changeState():void monkey. scream ();
+getState(): String }

Original design of class Monkey


Drawbacks of the design:
a) A lot of conditional statements in the method
behave()
b) It is not easy to add new state related behaviors

How to improve the design?

Idea: build a state class hierarchy to encapsulate


each state into a separate class
New design:
<<interface>>
Monkey
Client -state
+changeState():void
+behave(): void

HappyMonkey SadMonkey AngryMonkey


+changeState():void +changeState():void +changeState():void
+behave(): void +behave(): void +behave(): void

Design by encapsulating each state into a separate class

Back
The State Design Pattern

1. 定义客户程序需要的接

The State Design Pattern

Participants
• Context
– 定义客户程序需要的接口。Defines the
interface of interest to clients.

that
defines the current state.
–可以包含部分业务逻辑
The State Design Pattern

• State
defines an interface for encapsulating the
behavior associated with a particular state
of the Context.
• State subclasses
each subclass
associated with a state of the Context.
The State Design Pattern
When to use state pattern?
a) 当对象的行为依赖于状态,而该对象必须根据其状
态(在运行时)改变其行为 When an object‘s
behavior depends on its state, and it must change
its behavior (at run-time) depending on that state.
b) 当操作带有大量与状态相关的、多部分的条件语句
When operations have large, multipart conditional
statements that depend on the object's state.
– The State pattern puts each branch of the
conditional in a separate class.
– This lets you treat the object's state as an
object in its own right that can vary
independently from other objects.
The State Design Pattern
协作关系 (Collaborations)
a) Context代表状态相关的请求。Context delegates
state-specific requests to the current
ConcreteStateobject.
b) Context可以将自己作为一个对象通过参数传递给
状态子类对象,从而可以让状态对象访问Context
类的方法。A context may pass itself as an
argument to the State object handling the
request. This lets the State object access the
context if necessary.
The State Design Pattern
c) 客户对象先创建一个具体的状态类的对象,然后,
在创建Context对象的时候,通过参数传递给
Context对象。此后,客户程序就不必与该状态
对象直接交互。Context is the primary
interface for clients. Clients can configure a
context with State objects. Once a context is
configured, its clients don’t have to deal with
the State objects directly.
d) 状态转换: Context类或具体的状态子类负责
Either Context or the ConcreteState
subclasses can decide which state succeeds
another and under what circumstances.
The State Design Pattern
State st = new StateA();
:Client Context c = new Context(st);
main() c.request(data);

request(data)

:Context st.handle(this, data)


+Context(Strategy st)
+request(data); st.handle(this, data)
+method()

c.method()

Typical Collaborations of the state design pattern


The State Design Pattern

关于状态的转换问题:
a) 是否所有的状态子类对象都需要由客户类创建,
然后再传递给Context类呢?
b) 还是客户类只创建一个“种子对象”,然后,
传递给Context类;再由Context类根据状态变
化的情况,负责创建所有的其它的对象呢?

回答:两种处理方法都可以,视具体情况而定
The State Design Pattern

Because all state-specific code lives in a State


subclass, new states and transitions can be
added easily by defining new subclasses.

Introducing separate objects for different states


makes the transitions more explicit. Also, State
objects can protect the Context from
inconsistent internal states.
Back
持续30秒

持续8秒 持续60秒

交通灯控制软件状态图
TrafficLightGUI 创建一个具体的状态对象,
并且传递给Context
Context
-light: LightState
+Context(LightState lt) 具体的子类负责改变状态
+getColor(): Color
+doAction (): void 调用performTask()
+setState(String st): void LightState
+setupStateObj(): LightState +getCurrentState(): String
+setupContext(Context cxt): void
light +performTask(): void
+setColor(): Color
决定状态对象 +changeState(): void

Red Yellow Green


+performTask(): void +performTask(): void +performTask(): void
+setColor(): Color +setColor(): Color +setColor(): Color
+changeState(): void +changeState(): void +changeState(): void
交通信号灯控制软件-设计1
• 关于主用户界面TrafficLightGUI
• Extends JFrame
• 自动更新图形界面:
– 利用JFrame类的paint()方法,该方法在
TrafficLightGUI生成的时候,将会自动被调用。
– 在paint()方法中,使用了repaint()方法,该方
法将自动调用将用paint()。
• 停顿效果:
– 使用了Thread类的wait()方法。产生停顿效果,
从而模拟了交通信号灯。
交通灯控制软件图形界面
1) rs = new Red();
TrafficLightGUI
cxt = new Context(rs);
2) rs.setupContext(cxt);
3) cxt.setState(TrafficLight.RED);
Context 4) color = cxt.getColor(); doAction()
-light: LightState cxt.doAction(); 被反复调用
+Context(LightState lt)
+getColor(): Color
+doAction (): void 调用performTask()
+setState(String st): void LightState
+setupStateObj(): LightState +getCurrentState(): String
+setupContext(Context cxt): void
light +performTask(): void
获得状态对象 +setColor(): Color
+changeState(): void

Red Green Yellow


+performTask() +performTask() +performTask()
+changeState() +changeState() +changeState()
+setColor() +setColor() +setColor()
TrafficLightGUI 在Context对象中,保持3个
子状态对象,而不会生成任
Context 何新的对象
-light: LightState ØredState,
-redState = new Red() ØgreenState
-greenState = new Green() ØyellowState
-yellowState = new Yellow()
+setupStateObj(): LightState 决定使用哪个子状态对象
LightState
light +getCurrentState(): String
+setupContext(Context cxt): void
+performTask(): void
+setColor(): Color
+changeState(): void

Red Green Yellow


+performTask() +performTask() +performTask()
+changeState() +changeState() +changeState()
+setColor() +setColor() +setColor()
本程序的交互情况
1) 【在客户类中】客户类首先创建Red类的对象,在创建Context
类的对象的时候,将Red类的对象以参数的形式传给Context类
的对象cxt。
rs = new Red();
cxt = new Context(rs);
2)【在客户类中】在状态类中还需要保持Context类的对象,因此需
要调用
rs.setupContext(cxt);
将刚刚创建的Context对象cxt传递给状态类
3) 【在客户类中】还需要给Context类的状态变量state赋予初始值
cxt.setState(TrafficLight.RED);
4) 【在客户类中循环调用】在方法runTrafficLights()中,使用语句
color = cxt.getColor();
cxt.doAction();
反复调用Context类的方法,以便产生循环显示灯的颜色的效果。
第4步的进一步解释
• 【在Context类中】每当调用cxt.doAction()的时
候,相应地状态子类的doAction()将会被调用,
changeState()也将会被调用
• 【在状态类中】 changeState()负责反复更新
Context类中的state变量
• 【在Context类中】 Context类的setupStateObj()根据新的
状态,决定使用某个状态子类对象light
light.performTask()
public class TrafficLightGUI extends JPanel{
private TrafficLight rs;
private Context cxt;
private Color color;
public TrafficLightGUI(){
setBackground(Color.cyan);
setUpStateContext();
}
private void setUpStateContext(){
rs = new Red(); //创建状态子类对象
cxt = new Context(rs); //创建Context类对象,传入参数rs
rs.setupContext(cxt); // 将cxt赋值给TrafficLight变量context
cxt.setState(TrafficLight.RED); //将RED状态传给Context
//类的state
}
private void runTrafficLights(){
color = cxt.getColor(); //获得当前颜色
cxt.doAction(); //进行操作,转换状态等等
}
public void paint(Graphics g){
super.paint(g);
try{
runTrafficLights();

// Paint the traffic light

Thread.sleep(2000);
repaint(); //产生循环
}catch(InterruptedException e){
e.printStackTrace();
}
}
private static void createAndShowGUI(){
JFrame f = new JFrame("State Pattern-Traffic Light");
TrafficLightGUI tf = new TrafficLightGUI();
f.getContentPane().add(tf);
f.setVisible(true);
}
public static void main(String args[]) {
Runnable doCreateAndShowGUI = new Runnable() {
public void run() {
createAndShowGUI();
}
};
SwingUtilities.invokeLater(doCreateAndShowGUI);
}
}
public class Context {
private TrafficLight lightObj, redObj,
greenObj, yellowObj;
private String state;
public Context(TrafficLight lt){
lightObj = lt; 一次性产生三个
redObj = new Red(); 状态子类对象,
greenObj = new Green();
yellowObj = new Yellow(); 避免创建更多的
} 对象
public String getLightState() {
return lightObj.getCurrentState();
}
public Color getColor(){
return lightObj.setColor();
}
public void doAction() { 反复由客户类
lightObj = setupStateObj(); 调用的方法
lightObj.performTask();
}
public void setState(String st){
state = st;
} 根据状态不同,
public TrafficLight setupStateObj(){
if( state.equals(TrafficLight.RED)){ 决定使用不同
lightObj = redObj; 的对象
lightObj.setupContext(this);
}
else if( state.equals(TrafficLight.GREEN)){
lightObj = greenObj;
lightObj.setupContext(this);
}
else if(state.equals(TrafficLight.YELLOW)){
lightObj = yellowObj;
lightObj.setupContext(this);
}
return lightObj;
}
}
public abstract class LightState{
protected String state=null;
protected LightState traffLight = null;
public static final String RED = "Red";
public static final String YELLOW = "Yellow";
public static final String GREEN = "Green";
protected Context cxt;

public String getCurrentState(){


return state;
}
public void setupContext(Context cxt){
this.cxt = cxt;
}
public abstract void performTask();
public abstract Color setColor();
public abstract void changeState();
}
public class Green extends LightState{
public Green() {
state = GREEN;
}
public Color setColor(){
return Color.green;
}
public void performTask() {
Surveillance.takePictures();
Surveillance.doStatistics();
changeState();
} 在改变状态变量
public void changeState(){
state = YELLOW; 的同时,更新
cxt.setState(state); Context类中的
} 状态变量
}
public class Red extends LightState{
• public Red() {
state = RED;
}
public Color setColor(){
return Color.red;
}
public void performTask() {
Surveillance.takePictures();
Surveillance.doStatistics();
changeState();
}
public void changeState(){ 在改变状态变量
state = GREEN; 的同时,更新
cxt.setState(state); Context类中的
}
} 状态变量
public class Yellow extends LightState{
public Yellow(){
state = YELLOW;
}
public Color setColor(){
return Color.yellow;
}
public void performTask() {
Surveillance.takePictures();
Surveillance.doStatistics();
changeState();
} 在改变状态变量
public void changeState(){
state = RED; 的同时,更新
cxt.setState(state); Context类中的
} 状态变量
}
• 在Context类中保持String类型的状态变量state
• 在TrafficLight类中保持Context类的对象cxt
• 在Context类中,调用状态类的方法
setupContext(Context)
将Context对象传入到TrafficLight类中

• 在状态类中,调用context类的setState(state)方法,
对Context类的state变量进行更新
• 在Context类中,首先统一创建三个状态子类的对象。
然后,在运行时,根据state变量的情况,决定使用
哪个状态子类对象。
本设计的优点:
1. 在本图形界面的设计中,没有与状态相关的条
件语句。因此,在对状态类添加一个新的状态
时或者修改状态类的子类与状态相关的代码的
时候,不需要修改客户类TrafficLightGUI。
2. 在修改某个状态子类的代码的时候,不需要修
改Context类的代码。
3. 在增加新的状态子类的情况下,需要少许修改
状态类的changeState()方法与Context类中的
相应代码。
【例3】银行业务问题。
Consider a business account at a bank. Such an
account can exist in any one of the following three
states at any given point of time:

-1000 0 2000 balance


balance >= 2000

withdraw deposit deposit withdraw

withdraw

deposit
0 < balance <2000 -1000 < balance < 0
transaction fee ($2) transaction fee ($5)

State transaction diagram


• The banking system is designed as
below
• See next page
BankAcctClientUI
objState
BankContext BankContext
balance: double
objState: State
+getState():String
+setStateObj(objState:State):void
+deposit(amt: double): void
+withdraw(amt: double): void
+getBalance(): double
+updateBalance(bal: double)
+isOverDrawnLimitHit(): boolean
保持BankContext类 更新在BankContext中
保持一个State类的一个引用 的引用. 该对象由 的balance
objState,维护banlance与 setContext方法传入 将具体的状态子类对象
state 传递给BankContext
State initState = new TransactionFeeState();
accContext = new BankContext(initState, "100 200 300 4000");
BankAcctClientUI accContext.deposit(2500);

BankContext BankContext
balance: double
objState: State
+getState():String
+setStateObj(objState:State):void
+deposit(amt: double): void
+withdraw(amt: double): void
+getBalance(): double
+updateBalance(bal: double)
+isOverDrawnLimitHit(): boolean
:ClientGUI :BankContext :TransactionState :State

deposit(2500)

updateBalance()

Sequence diagram for depositing 2500 dollars


BankContext class
1. 保持数据 (Maintains data):
• balance,
• account number
• State object, and
• the transaction limits
2. 给客户程序提供基本的存款与取款方法。
Offers the basic methods
deposit(double amt) and
withdraw(double amt)
inside which the same methods inside
a state subclass will be called.
State 类:
• 负责转换状态
• 负责将当前具体状态传递给BankContext类

State 子类:
• 负责存款、取款
• 负责更新BankContext类中的balance
本类有
保持账
户信息
的责任

在状态类中调
用这个方法以
便将当前状态
对象传递给
Context类
在状态类
中调用这
两个方法
以便更新
余额
public abstract class State {
private String acctNumber;
protected double balance =0;
protected String state;
protected State stateObj;
protected BankContext context;
protected void changeState(){
balance = context.getBalance();
if(balance<0&&balance >= BankContext.OVERD_LIMIT)
state = OVERDRAWNSTATE;
else if (balance >= BankContext.MIN_BALANCE)
state = NOFEESTATE;
else if (balance >= 0&&balance<BankContext.MIN_BAL)
state = FEESTATE;
else
state = ERRORSTATE;
passStateObjToContext();
}
public void passStateObjToContext(){
if(state.equals(OVERDRAWNSTATE) )
stateObj = new OverDrawnState();
else if (state.equals(NOFEESTATE) )
stateObj = new NoTransactionFeeState();
else if (state.equals(FEESTATE))
stateObj = new TransactionFeeState();
context.setStateObj(stateObj);
}
public String getState(){
return state;
}
public void setContext(BankContext context){
this.context = context;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
public abstract boolean isOverDrawnLimitReached();
}
public class NoTransactionFeeState extends State{
private boolean overDrawnLismitFlag = false;
public NoTransactionFeeState(){
state = NOFEESTATE;
}
public void deposit(double amount){
balance = context.getBalance() + amount;
context.updateBalance(balance);
changeState();
}
public void withdraw(double amount){
if ((context.getBalance() - amount) > BankContext.OVER_LIMIT){
balance = context.getBalance() - amount;
context.updateBalance(balance);
changeState();
}
else {
overDrawnLismitFlag = true;
}
}
public boolean isOverDrawnLimitReached(){
return overDrawnLismitFlag;
}
}
public class TransactionFeeState extends State{
private boolean overDrawnLismitFlag = false;
public TransactionFeeState(){
state = FEESTATE;
}
public void deposit(double amount){
balance = context.getBalance() - BankContext.TRANS_FEE_NORMAL;
balance = balance + amount;
context.updateBalance(balance);
changeState();
}
public void withdraw(double amount){
if ((context.getBalance() - BankContext.FEE_NORMAL - amount) >
BankContext.OVERDRAW_LIMIT) {
balance = context.getBalance() - BankContext.FEE_NORMAL;
balance = balance - amount;
context.updateBalance(balance);
changeState();
}
else{
overDrawnLismitFlag = true;
}
}
}
用户图形界面
本设计的优点:可扩展性超好
• 因为在客户类与Context类中,都不包含关于与
状态有关的条件语句,因此
– 当要修改某个状态子类的时候,不需要修改客
户类与Context类;
– 当要添加一个新的状态子类的时候,不需要修
改客户类与Context类,只需要少许修改状态
子类的changeState方法

Back
State pattern Strategy pattern
状态相关的行为 不是状态相关的行为
The behavior contained in The behavior contained in each
each State object is specific Strategy object is a different
to a given state of the algorithm to provide a given
associated object. functionality.
状态对象可以负责更新配置给 由客户类创建策略子类对象,并且传递给
Context类的状态对象。 Context对象。
A given State object itself A client application using the context
can put the context into a needs to explicitly assign a strategy
new state. to the context.
This makes a new State
object as the current State A Strategy object cannot cause the
object of the context, context to be configured with a
changing the behavior of the different Strategy object.
Context object.
State Pattern Strategy Pattern
状态的选择(转换)依赖于 由应用类选择策略子类对象
Context或者State对象 The choice of a Strategy object
The choice of a State is based on the application
object is dependent on need. Not on the state of the
the state of the Context Context object.
object.
有状态转换:可以由 没有状态转换
Context类或者State层次类
进行状态转换
可以将一些业务逻辑包含在 可以将一些业务逻辑包含在Context
Context类中(包括状态转换) 类中(没有包括状态转换)

Back
Contents of the lecture

4. Standard of Grid Computing


• 复杂科学计算(基因组计算),使用超级计算机
• 问题:
Ø 1)计算费用昂贵
Ø 2)有很多计算,超级计算机也不能胜任
• 你有什么想法?
方案:使用百万台、千万台计算机通过互联网连接共同计算
Ø 利用一切可以利用的资源
Ø 需要有中心服务器
Ø 需要有整合机制
Ian Foster defines a as a system
that:
1. 整合资源,将本来不属于中心控制的资源,进行合
作. oordinates resources that are not subject to
centralized control
2. 使用标准的,开放的,一般目的的协议。using
standard, open, general-purpose protocols and
interfaces
3. 提供有相当质量的服务。to deliver nontrivial
qualities of service.
1. Basic Concepts of Grid Computing

A lot of resources spreading over an enterprise


or service provider's area can provide
vRedundant (大庆,宝钢,大企业)
vReliable (大庆,宝钢,大企业)
services.
integration of
services and resources across
Ø Distributed 分布式的
Ø Heterogeneous 多样的
Ø Dynamic 动态的
virtual organizations, whether within a single
enterprise or extending to external resource-
sharing and service-provider relationships.
1. Basic Concepts of Grid Computing

分布式的,多样的,动态的

Grid integrates a wide variety of geographically distributed resources


Ø 网格计算中虚拟组织的概念
Ø In grid computing, a virtual organization (VO)
refers to a dynamic set of individuals or
institutions defined around a set of resource-
sharing rules and conditions
Ø All these virtual organizations share some
common interests among them. (例如蛋白质
折叠计算、药物研究计算).
1. Basic Concepts of Grid Computing

2 3
1. Main cluster server divides
Tasks into smaller subtasks 2 3
and parcel them to local
cluster servers
1
1
3
3
4 3
1 1
3
Database farm

2 3 4. Main cluster server aggregates complete


tasks and send data back to the dadabase
2 3
farm

2. local cluster servers find


available processing power 3. local cluster servers gather completed tasks from
on local PCs and
distributes subtasks into
local PCs and send data back to Main cluster
servers
网格计算机制
those PCs
1. Basic Concepts of Grid Computing

• 资源供应技术 Provisioning of Resources. Grid


computing consists of a family of technologies
for dynamically provisioning computing power
from a pool of resources.
• The resource pool can include:
Ø computing cycles
Ø file and data storage
Ø Caching
Ø network bandwidth
Ø databases and
Ø data warehouses
Ø application software
1. Basic Concepts of Grid Computing

.
a) The resource pool can be geographically
dispersed and
b) individual resources can vary widely in
Ø Capability
Ø Capacity, and
Ø Availability
Several grid-aware applications can share the
resource pool.
1. Basic Concepts of Grid Computing

:
Provisioning includes methods and
mechanisms for
Ø Locating (寻找)
Ø Authorizing (授权)
Ø Assembling (组装)
Ø Scheduling (计划)
Ø Releasing, and (释放、发布)
Ø Accounting (记账)
for resources and their usage.
1. Basic Concepts of Grid Computing

omputing
Grid Types First dimension describes
grid types:
Ø data grid,
Ø computational grid
Geographic grid. Second dimension
describes a grid's geographic reach:
Ø campus grid,
Ø statewide grid, and
Ø global grid.
1. Basic Concepts of Grid Computing

Third dimension reflects how to obtain these


resources. A service provider owns dedicated
grid resources and strictly monitor and control
their use, e.g., utility grid.

.
reflects membership or
partnership: e.g,
Ø enterprise-internal intragrids
Ø multisite extragrids
Ø business partner grid and
Ø peer-to-peer consumer grids
1. Basic Concepts of Grid Computing

reflects the type of application:


Ø Science (weather forecasting, land resource
statistics)
Ø Biology (e. g. bioinformatics)
Ø Sensors (pollution statistics)
Ø Astronomy
Industries that utilized the GRID computing power.
• 网格中间件:网格中间件是将许多资源应用粘合
在一起的粘合剂软件。
• 网格中间件是网格关键技术之一,其目的是为用
户提供具有同一编程接口的虚拟机器,支持复杂
应用问题的求解和广域网上各类资源的共享。
• 美国、英国都很重视这方面的研究。
Mobile Access
G
R
I Supercomputer, PC-Cluster
D

M
I
Workstation D
D
L
E Data-storage, Sensors, Experiments
W
A
R
E
Visualising
Internet, networks

网格中间件的作用-将许多资源应用粘合在一起的粘合剂软件
网格用户仅仅需要像使用市电一样使用网格计算
• 由于网格计算所涉及的资源都是在地理上广泛
分布的异构资源,所以网格计算特别注重资源
整合。这就要求网格中间件要具备
Ø屏蔽节点异构(Unix, Linux,Windows)
Ø优化资源选择(例如,计算能力)
Ø协同计算与资源动态监测
的功能。
• 网格中间件应该包括 资源监测组件
Ø资源监测组件
计算服务组件
Ø计算服务组件
Ø网格安全组件 网格安全组件
Ø容错服务组件 容错服务组件
Ø信息服务组件和 信息服务组件
Ø应用调度组件
应用调度组件
• 网格中间件是网格计算的核心,其主要
任务是利用分布于整个互联网的异构资
源,包括
Ø计算集群
Ø存储设备
Ø科学仪器等
• 通过构建一个同构的环境使得这些资源
能够为分布于各地用户提供协同服务,
达到在整个广域网范围内的计算资源共
享。
• 网格中间件的作用为使用一个唯一的接口,使得
用户能通过该接口将某项计算任务提交到网格,
而具体的计算程序可能运行在网络的任何地方。
• 其它例如
Øresource broker
Øreplica manager
等等的类似的软件组件协助中间件将计算任务分
配到最适合计算的节点。
• 对于使用中间件的用户来讲,这些细节被隐藏了
起来。用户仅仅关心计算结果,而不必关心哪些
计算任务被分配到哪些计算机。

Computing task

Result
网格中间件可以被看作是虚拟超级计算机的操作系统。
该“超级计算机”实际上包含许了许多在不同的站点
运行的许多独立的计算节点,但是对于用户来说,所
面对的似乎仅仅是一台独立的超级计算机。

Grid User
Super Computer
将某个网格想象成一台超级计算机
• 形象地说,可以理解在中间件的一侧,
是地理上广泛的分布的各种各样的资源,
在中间件的另外一侧,是许多虚拟组织,
每个组织都拥有它们自己网格应用。
Ø这些应用可以通过少许的由中间件提
供的接口访问这些异构的资源
大量异
构资源

Grid Middleware

天文爱好者 基因计算 天气爱好者


网格应
网格虚拟组织 网格虚拟组织 网格虚拟组织 用程序

网格计算中间件工作原理
• Grids and P2P的相似之处:使用地理上广泛分布
的资源
• Foster believes that grids and P2P computing
have much in
ØBoth approaches have the same objective:
-
• Grids and P2P的区别: But there is one difference
between them,
.
focus on top-down issues:

computing focus on bottom-up


issues, such as:

for many participants


5. standard of Grid Computing

: 全球网格论坛与Globus联盟制定标准
• Global Grid Forum (GGF) and Globus Alliance
focus on
Øarchitectures,
Øsoftware tool kits, and
Øapplications development.
• GGF published the Open Grid Services
Infrastructure (OGSI) in June 2003.
• It was intended to provide an infrastructure layer for
the Open Grid Services Architecture (OGSA).
5. standard of Grid Computing

• 网格计算标准OGSI(开发网格架构基础设施)
• The Open Grid Services Infrastructure (OGSI)
focuses on
Øinteroperable service features ,
Øinterfaces, and
Øprotocols,
including service invocation, management, and
data and security interfaces.
5. standard of Grid Computing

• 网格计算的新标准OGSA(开放网格服务架构)
• In Feb 2002, in the conference of Global Grid
Forum (GGF) held in Toronto, Canada,Globus
Project team and IBM proposed a new Grid
standard OGSA (Open Grid services
architecture).
ØIt Combines Globus standard and web
application standard
ØThe birth of OGSA, means business
application of grid computing is possible
5. standard of Grid Computing

两个标准提供的网格服务的框架
OGSA and OGSI provide a common
framework for grid services.
5. standard of Grid Computing

.
Published in 2003, Globus Toolkit (3.0) is an
open architecture and open-source.
Globus Toolkit has the components for
Ø security
Ø job submission and control
Ø data transfer
Ø databases
Ø Consistent system
Ø service interfaces
(http://toolkit.globus.org/toolkit/).
5. standard of Grid Computing

• GT-2 – pre standards


• GT-3 – Open Grid Services Infrastructure (OGSI)
• GT-4 – Web Services Resource Framework (WSRF), 04/29/2005
• GT-5 – published in 2010
• GT-6- published in 2014
GT-6-
GT-6-本实现了
最后的版GT-6-
• OGSI (开放网格服务基础架构);
• OGSA (开放网格服务架构);
• WSRF (Web服务资源架构);
• JSDL (任务提交描述语言);
• DRMAA (分布式资源管理应用API);
• …

.
u2003/10, IBM and China’s Ministry of Education
announced they have begun using grid
technology to enable universities across the
country to collaborate on
Øresearch,
Øscientific and
Øeducation
projects. (
• BOINC网格项目:BOINC (Berkeley Open
Infrastructure for Network Computing)

• 由加州大学,和伯克利大学开发的BOINC项目,
使得任何人可以使用家庭个人计算机在许多科学
研究领域的项目中贡献计算能力。
• 研究领域:数学,医学,分子生物学,气候学,
天体物理学。BOINC是一共同一个寻找公开志愿
者的学术项目。
• Folding@home网格项目:Folding@home
(abbreviated as FAH or F@h)
• 目的:研究蛋白质的正确折叠和错误折叠。

• Einstein@Home网格项目:
• 目的:使用从LIGO重力波探测器得到数据器得
到的数据研究旋转中子星。
• 美国NASA IPG项目:NASA IPG:
• IPG (Information Power Grid)是美国国家航空和
宇航局(NASA)的一个高性能计算与数据网格项
目。
• 使用IPG中间件,网格用户就可以从任何地方访问
广泛分布的异构资源。IPG的任务是为NASA的科
学与工程人员提供一个解决问题的平台。
• IPG的主要目标是建立一个网格环境原型:一个异
构的、分布计算、数据和仪器环境,以提供统一的
资源访问。IPG系统的主要应用领域为:高性能计
算、高能物理和海量数据存储。参见网址
(www.ipg.nasa.gov)
• NFCR 计算药物发现中心:NFCR (Centre for
Computational Drug Discovery)
• 计算药物发现项目。志愿者捐赠闲置计算能力。
• 目的:是发现治疗癌症的药物,使用计算的方法
筛选出小分子结构,至少可以缩短药物发现的周
期。
• 美国TeraGrid网格项目:国家科学基金会的
TeraGrid (http://www.teragrid.org/)
• 是巨型的研究计算的基础设施,在2001年投资
5300万美元建成,其目的是结合五大计算和数据
管理设施和支持许多另外的学院和研究实验室。
• TeraGrid是开放的科学发现网格计算的基础设施。
它结合了具有领导地位的资源的十一个伙伴站点,
以便创建一种集成的,永久性的计算资源。
• 使用高性能的网络连接,TeraGrid集成高性能计
算机、数据资源和工具和美国国家的高端的实验
设施。
TeraGrid

• The TeraGrid is launched by the


[1] Ian Foster and Carl Kelsselman, Grid 2,
blue print for a new computing
infrastructure. 2nd Edition.
see: www.mkp.com/grid2
[2] Globus Toolkit® 4: Programming Java
Services, published by Morgan Kaufmann
Publishers / Elsevier.
[3] Borja, sotomayer, globus Toolkit 4,
programming Java services
Professor:
Yushan (Michael) Sun
Fall 2016
1
Contents of the lecture

1. Introduction of the
2. Official Diagram of the Visitor Design
Pattern
3. Design Example Using the Visitor
Pattern

2
3
Bird CatFamily

4
Bird CatFamily

5
在此类
中调用
Animal
层次类

Bird CatFamily

6
在此类
中调用
Animal
层次类

Bird CatFamily

7
Example 2: tax computation problem (税收问题)

Example 2: tax computation problem (税收问题)


• In US, there are many kinds of taxes, including
– enterprise tax and
– individual tax,
– etc.,.

• The taxes can be expressed by using a


hierarchy of classes as below.
• To compute the tax, we can use a class with
main methods to invoke the tax hierarchy to get
tax rates, etc.
8
IndividuleTax

9
Example 2: tax computation problem (税收问题)

:
Distributing all these operations across the
various node classes leads to a system that's
hard to
– understand,
– maintain, and
– change.

10
Example 2: tax computation problem (税收问题)

:
For example,
• Poor maintainability: It will be confusing to
have a lot of of code in so many
nodes.
: adding a new operation
usually requires recompiling all of these classes,
• See next page

11
IndividuleTax

12
Example 2: tax computation problem (税收问题)

:
n Separate the main functionalitie(s) of the classes,
i.e., let the class be independent of the
operations that apply to them.

13
调用Tax
类的方法,
达到计算
tax的目的

IndividuleTax

14
Example 2: tax computation problem (税收问题)

• 进一步改善设计 (More Improved design)

• In order for the above design more effective,


we change the above design a little bit
• The new design is in the next page

15
新设计引入 将TacCalculator 改变为
accept()方法 TaxVisitor类。将所有的
方法都改为访问方法。为
每个类单独设计一个访问
方法,以便获得相应的
Tax信息。

IndividuleTax

16
Example 2: tax computation problem (税收问题)
新设计的解释
In the improved design
1. 改进类名 Class name TacCalculator has been
changed into TaxVisitor
2. 改进方法名 Method names in class TaxVisitor
have been changed into the form visitxxx:
Ø visitxxx means that this method is to get
information from class xxx and calculate tax
for class xxx.
3. 增加accept()方法。In each subclass of class
Tax, add a method named accept() to pull in a
specific visit method.
17
Example 2: tax computation problem (税收问题)

为什么要引入访问者方法与接受方法:

意图:利用accept()与visit()方法,在Tax层次类与
TaxVisitor之间精心地设计一个接口,以便使得两
个类能通过该接口连接起来,例如:

ElectronicTax TaxVisitor

ElectronicTax TaxVisitor
18
Example 2: tax computation problem (税收问题)

四个软件天才--四人帮(Gof)照片

类 中的
accept(TaxVisitor v)
v. ()
}
19
Example 2: tax computation problem (税收问题)
两个对象是怎样被链接在一起的呢?
Client
main()

使用accept方法,而不是通过构造方法
将访问者对象拉入

ElectronicTax (this)
+accept(Visitor v)
tax.getData()
+getData:double

v. visitElectronicTax()

20
Interactions involved in the above design
Example 2: tax computation problem (税收问题)

:Client

(tax)

:ElectronicTax :TaxVisitor

Client 类负责创建两个类的对象并且使用accept方法
将两个类连接在一起
Back
21
22
23
访问者模式构件的解释
u Visitor class declares a Visit operation for
each class of Element in the object structure.
Ø The operation's name and signature identifies
the class that sends the Visit request to the
visitor. For example, method
u Let the visitor determine the concrete class of
the element being visited. Then the visitor can
access the element directly through its
particular interface.

24
访问者模式构件的解释
ConcreteVisitor
Ø Implements each operation declared by Visitor.
uEach operation implements a fragment of the
algorithm defined for the corresponding class
of object in the structure.
Ø Provides the context for the algorithm and stores
its local state, which
during the traversal of the structure.

25
Element
• Defines an Accept operation that takes a visitor
as an argument.

ConcreteElement (ElementA, ElementB)


• Implements an “accept” operation that takes a
visitor as an argument.
• May also implement some methods to help the
visitor to realize some functionalities. For example,
getData in Tax hierarchy
26
ObjectStructure (Program) ( )
• Can enumerate its elements.
• May provide a high-level interface to allow the
visitor to visit its elements.
• May either be a composite or a collection such
as a list or a set.

• 该类可以使用一个聚合结构例如Java ArrayList
将被访问对象集合在一起,然后再使用一个循环
语句批量调用accept方法。

Back
27
28
假如我们要为一个电动自行车专卖商店写一个销售程
序。现在已经有一个层次类如下可供使用。
Battery BatteryBag BatteryCable BatteryChanger Controller
+getPrice +getPrice +getPrice +getPrice +getPrice
+getDescription +getDescription +getDescription +getDescription +getDescription

EBike
+getPrice
+getDescription

Motor Throttle BrakeHandle Wheel Composite


+getPrice +getPrice +getPrice +getPrice +getPrice
+getDescription +getDescription +getDescription +getDescription +getDescription

WholeBike
+getPrice 29
+getDescription
Task: we need to write a management system for
the clerks to use in store?
– To compute the price total
– To check

怎样设计我们的程序呢?
: Just write a client class with a main
method to call the getPrice() method in each of
the concrete classes to get the prices and then
add them up.

30
Battery BatteryBag BatteryCable BatteryChanger Controller
+getPrice +getPrice +getPrice +getPrice +getPrice
+getDescription +getDescription +getDescription +getDescription +getDescription

EBikeGUI EBike
+getPrice
+main() +getDescription

Motor Throttle BrakeHandle Wheel Composite


+getPrice +getPrice +getPrice +getPrice +getPrice
+getDescription +getDescription +getDescription +getDescription +getDescription

WholeBike
+getPrice
+getDescription

: write a class with a main method, to call the getPrice()


method in the concerned classes and then add them up. 31
: Design using the
Reason: Because the types of the parts don’t
change often, and the prices of the parts will
change very often.

设计要点:

32
With the Visitor pattern, you define
two class hierarchies:
ØElement class hierarchy-
ØThe class to be visited, and
ØVisitor class hierarchy-
Ødefine operations on the elements

33
eed an abstract parent class Visitor for
all visitors of an abstract syntax tree.
Visitor must declare an operation for each
node class.

34
EBikeUI Visitor

Battery BatteryBag BatteryCable BatteryChang Controller


+accept(v: Visitor) +accept(v: Visitor) +accept(v: Visitor) erVisitor)
+accept(v: +accept(v: Visitor)
+getPrice() +getPrice() +getPrice() +getPrice() +getPrice()
+getDescription() +getDescription() +getDescription() +getDescription() +getDescription()

EBike
+accept(v: Visitor)
+getPrice()
+getDescription()

Motor Throttle BrakeHandle Wheel Composite


+accept(v: Visitor) +accept(v: Visitor) +accept(v: Visitor) +accept(v: Visitor) +accept(v: Visitor)
+getPrice() +getPrice() +getPrice() +getPrice() +getPrice()
+getDescription() +getDescription() +getDescription() +getDescription() +getDescription()

WholeBike
+accept(v: Visitor)
+getPrice() 35
+getDescription()
获得某个配 获得某个配
件的价格 件的信息

36
Client

Battery
pv.visitBattery( );
+accept(Visitor v)
+getPrice:double
+getDescription

Interactions in the design 37


38
abstract class EBike{
public abstract void accept(Visitor vis);
public abstract double getPrice();
public abstract String getDescription();
}

39
public class Motor extends EBike {
public double getPrice(){
return 430.00;
}
public String getDescription(){
return "Super Motor...";
}
public void accept(Visitor v) {
System.out.println("Motor has been visited.");
v.visitMotor(this);
}
}
40
public class Throttle extends EBike {
public double getPrice(){
return 155.00;
}
public String getDescription(){
return "Super Throttle...";
}
public void accept(Visitor v) {
System.out.println("Throttle has been visited.");
v.visitThrottle(this);
}
}
41
public class WholeBike extends Composite {
public WholeBike() {
super.add(new Battery());
super.add(new BatteryBag());
super.add(new BatteryCable());
super.add(new BatteryChanger());
super.add(new BrakeHandle());
super.add(new Controller());
super.add(new Motor());
super.add(new Throttle());
super.add(new Wheel());
}
public void accept(Visitor v) {
System.out.println("WholeBike has been visited.");
super.accept(v);
}
}
42
abstract class Composite extends EBike {
private Vector parts; // = new Vector(10);
public Composite() { parts = new Vector(20); }
public void add(EBike eBikePart) { parts.add(eBikePart); }
public double getPrice() {
double total=0;
for (int i=0; i < parts.size(); i++) { total += ((EBike)
parts.get(i)).getPrice(); }
return total;
}
public String getDescription() {
String des = null;
for (int i=0; i < parts.size(); i++){ des += ((EBike)
parts.get(i)).getDescription(); }
return des;
}
public void accept(Visitor v) {
for (int i=0; i < parts.size(); i++) { ((EBike) parts.get(i)).accept(v); }
}
} 43
public class PriceVisitor extends Visitor {
private double total;
private double batteryPrice, batteryBagPrice, private double batteryCablePrice, batteryChangerPrice,
private double brakeHandlePrice,
controllerPrice, motorPrice, throttledPrice, wheelPrice;

public PriceVisitor() { total = 0.0; }

public double getPriceTotal() { return total; }


public void visitBattery(Battery e){ batteryPrice=e.getPrice(); total += batteryPrice;
}
public void visitBatteryBag(BatteryBag e){ batteryBagPrice=e.getPrice(); total += batteryBagPrice; }
public void visitBatteryCable(BatteryCable e){ batteryCablePrice=e.getPrice(); total += batteryCablePrice; }
public void visitBatteryChanger(BatteryChanger e){ batteryChangerPrice=e.getPrice(); total +=
batteryChangerPrice; }
public void visitBrakeHandle(BrakeHandle e){brakeHandlePrice=e.getPrice(); total += brakeHandlePrice; }
public void visitController(Controller e){ controllerPrice=e.getPrice(); total += controllerPrice; }
public void visitMotor(Motor e){ motorPrice=e.getPrice(); total += motorPrice; }
public void visitThrottle(Throttle e){ throttledPrice=e.getPrice(); total += throttledPrice; }
public void visitWheel(Wheel e){ wheelPrice=e.getPrice(); total += wheelPrice; }
public void visitWholeBike(WholeBike e){ total += e.getPrice(); }
public double getBatteryPrice(){ return batteryPrice; }
public double getBatteryBagPrice(){ return batteryBagPrice; }
public double getBatteryCablePrice(){ return batteryCablePrice; }
public double getBatteryChangerPrice (){ return batteryChangerPrice; }
public double getBrakeHandlePrice(){ return brakeHandlePrice; }
public double getControllerPrice(){ return controllerPrice; }
public double getMotorPrice (){ return motorPrice; }
public double getThrottlePrice(){ return throttledPrice; }
public double getWheelPrice(){ return wheelPrice; }
} 44
计算机部件销售的例子

【例3】需求:计算机部件销售的例子。假设要写
一个为计算机商店使用的计算机部件销售软件。该
软件要求用户能使用友好的图形界面选择要购买的部
件,提交,然后分别列出各个部件的名称与单价,以
及总价格。

设计:考虑到计算机部件的种类相对固定,而价格经
常变化,所以我们采取使用访问者模式进行设计。设
计类图如下。

45
计算机部件销售的例子
ComputerPartsGUI Visitor

PriceVisitor PartsInfoVisitor

CompositeStructure ComputerParts
+attach(ComputerParts e)
+attach(ComputerParts e) +getPrice()
+detach(ComputerParts
+detach(ComputerParts e)
e) +getDescription()
+accept(Visitor v)
+accept(Visitor v) +accept(Visitor v)

Motherboard Microprocess Memory VideoCard Monitor


+getPrice() or
+getPrice() +getPrice() +getPrice() +getPrice()
+getDescription() +getDescription() +getDescription() +getDescription() +getDescription()
+accept(Visitor v) +accept(Visitor v) +accept(Visitor v) +accept(Visitor v) +accept(Visitor v)

利用访问者模式设计的计算机部件销售软件系统
46
设计要点:
• 每个计算机部件类都有一个getPrice()方法,与
一个accept()方法。
• PriceVisitor通过accept()方法,调用getPrice()
方法,达到计算价格的目的。
• 类似地,PartsInfoVisitor类负责调用
getDescription方法,实现获取部件的具体描述。

47
计算机部件销售的例子

• 本设计与例2设计的不同之处:
在本设计中,使用了CompositeStructure类。
ComputerPartsGUI类根据用户请求提交的计算机部
件名称,
Ø创建各个相应的部件对象,然后,
Ø将这些对象添加到复合对象CompositeStructure
中。

• CompositeStructure对象负责接受访问者PriceVisitor
对象,对该复合对象所包含的各个对象访问。
48
计算机部件销售的例子

关于CompositeStructure:
• 在CompositeStructure类中,封装了长度可以弹
性增长的数据结构ArrayList。
• 在CompositeStructure对象中,可以添加许多等
待访问的对象,而不必关心数组越界问题。
• 类CompositeStructure负责“批量”接受访问者
访问所需要被访问的对象。

49
计算机部件销售的例子
CompositeStructure comStruct = new CompositeStructure();
While(true){
ComputerPartsGUI if(part != null){
ComputerParts part = new Memory()
comStruct.attach(part);
attach(part) }
PriceVisitor pv = new PriceVisitor();
PartsInfoVisitor iv = new PartsInfoVisitor();
comStruct.accept(pv);
Visitor
CompositeStructure
+attach(ComputerParts e)
+attach(ComputerParts e)
+detach(ComputerParts
+detach(ComputerParts e)
e)
+accept(Visitor v)
+accept(Visitor v) ComputerParts PriceVisitor PartsInfoVisitor
+getPrice() visitMemory()
+getDescription() visitMonitor()
AllParts.accept(v) +accept(Visitor v)

Motherboard Microprocess Memory VideoCard Monitor


+getPrice() or
+getPrice() +getPrice() +getPrice() +getPrice()
+getDescription() +getDescription() +getDescription() +getDescription() +getDescription()
+accept(Visitor v) +accept(Visitor v) +accept(Visitor v) +accept(Visitor v) +accept(Visitor v)

利用访问者模式设计的计算机部件销售软件系统 50
• 在以上客户程序的代码实现的中,首先创建了
CompositeStructure类的对象,
• 然后调用了该类的方法accept(PriceVisitor pv) 与
accept(InventoryVisitor iv)。
• 在以上的accept方法中,采用了一个循环语句,但是
没有条件语句。也就是说,CompositeStructure类的
对象负责将等待访问的Part对象保存,但是并不关心
确切地哪个对象被保存了。
• 当需要接受访问者的时候,使用一个循环语句,遍
历所有的待接受访问的对象,使得每个对象都接受
访问。

51
计算机部件销售的例子-代码
在下面用户图形界面源代码中,省略了大量的语句
public class ComputerPartsGUI extends JFrame implements ItemListener{
private void createPartObjAndVisitParts(ActionEvent e){
ComputerParts part = null;
PriceVisitor pv = new PriceVisitor();
PartsInfoVisitor iv = new PartsInfoVisitor();
CompositeStructure comStruct = new CompositeStructure();

//循环语句
if(part != null){
comStruct.attach(part);

comStruct.accept(pv);
comStruct.accept(iv);
}
} 52
计算机部件销售的例子-代码
public class CompositeStructure{
private ArrayList<ComputerParts> parts;
public CompositeStructure(){
parts = new ArrayList<ComputerParts>();
}
public void attach(ComputerParts equip){
if(equip != null)
parts.add(equip);
}
public void detach(ComputerParts equip){
if(equip != null)
parts.remove(equip);
}
public void accept(Visitor v){
int len =parts.size();
for (int i=0; i < len; i++){
ComputerParts part = parts.get(i);
part.accept(v);
}
}
} 53
计算机部件销售的例子-代码

public abstract interface ComputerParts {


public abstract void accept(Visitor vis);
public abstract String getName();
public abstract double getPrice();
public abstract String getDescription();
}

54
计算机部件销售的例子-代码

public class Microprocessor implements ComputerParts{


public static final String NAME = "Microprocessor";
private final double PRICE = 80.00;
public static final String FEATURES = "Microprocessor. Intel BJ786";
public String getName(){
return NAME;
}
public double getPrice(){
return PRICE;
}
public String getDescription(){
return FEATURES;
}
public void accept(Visitor v){
System.out.println("Microprocessor has been visited.");
v.visitMicroprocessor(this);
}
}
55
计算机部件销售的例子-代码
public abstract interface Visitor{
public abstract void visitComputerCase(ComputerCase e);
public abstract void visitPowerSupply(PowerSupply e);
public abstract void visitMotherboard(Motherboard e);
public abstract void visitMicroprocessor(Microprocessor e);
public abstract void visitMemory(Memory e);
public abstract void visitDriveController(DriveController e);
public abstract void visitHardDiskDrive(HardDiskDrive e);
public abstract void visitCDDrive (CDDrive e);
public abstract void visitDVDDevice (DVDDevice e);
public abstract void visitMonitor (Monitor e);
public abstract void visitKeyboard (Keyboard e);
public abstract void visitMouse (Mouse e);
public abstract void visitFan (Fan e);
public abstract void visitVideoCard(VideoCard e);
} 56
计算机部件销售的例子-代码
本类省略了大量代码
public class PriceVisitor implements Visitor{
private double total =0 ;
public double price = 0;
ArrayList<Double> partsPrices;
public PriceVisitor() {
partsPrices = new ArrayList<Double>();
}
public void visitComputerCase(ComputerCase e) {
price = e.getPrice();
partsPrices.add(new Double(price));
total += price;
}
public ArrayList<Double> getPartsPrices() {
return partsPrices;
}
public double getPriceTotal(){
return total;

}
} Back
57
58
1) 对象结构包含很多个子类,而这些类有不同的接口。
你需要针对不同的类进行不同的操作。An object
structure contains many classes of objects with
differing interfaces, and you want to perform
operations on these objects that depend on their
concrete classes.

注:这就是为什么访问者类要针对每个被访问的类都设计一个不
同的接口的原因。事实上,如果每个子类都有相同的接口,包括
构造方法、其它方法、参数都一致,则访问者类则只需要设计一
个访问方法,在该方法中,含有一个用于区别不同的被访问的子
类的参数即可,例如,可以使用被访问者基类作为参数类型。
59
2)许多不同的且不相干的操作需要施加于对象结构,
而你想要避免这些不同的操作污染这些类。Many
operations need to be
performed on objects in an object structure, and
you want to avoid “polluting” their classes with
these operations.

60
3)对象结构类很少改变,但是你需要经常地在这些
结构体上增加新的运算。
he classes defining the object structure rarely
change, but you often want to define new
operations over the structure.

61
Collaborations

1. A client that uses the Visitor pattern must create


a ConcreteVisitor object and then traverse the
object structure, visiting each element with the
visitor.
2. When an element is visited, it calls the Visitor
operation that corresponds to its class. The
element supplies itself as an argument to this
operation to let the visitor access its state, if
necessary.

62
Consequences

1.
. Visitors make it easy to add
operations that depend on the components of
complex objects. You can define a new
operation over an object structure simply by
adding a new visitor.

63
Consequences

2.
. (例如,将计算总价格放
在一个具体的visitor类中)

64
Consequences

1.
• Each new ConcreteElement gives rise to a new
abstract operation on Visitor and a corresponding
implementation in every ConcreteVisitor class.

65
讨论: 访问者模式的重点

• 什么是访问者模式的重点?
• 回答: 用于使得被访问者与访问者之间建立自动
访问的accept方法是重点。该方法建立了两个层
次类之间的关联。该方法使得自动访问成为可能。

• 注: 另外,类objectStructure类对于批量访问很重
要。另外使用此类,可以使得客户类包含较少的
条件语句。能够有效地做到责任分离。

• 结论: 要写好accept方法与objectStructure
Back 66
Professor:
Yushan (Michael) Sun
Fall 2016
Contents of this lecture
Introductory example to the mediator pattern

【例1】:机场指挥塔的功能

a) 指挥起飞:所有的飞机必须接到起飞的命令才能起飞
b) 指挥降落:所有的飞机必须接到降落的命令才能降落
c) 通讯:飞机和指挥塔通讯;所有的飞机不能直接通讯
• 通讯方式
A1 A2

A8 A3

Tower

A7 A4

A6 A5
Introductory example to the mediator pattern

Zhang

Wang Huang

Li Zhao
Introductory example to the mediator pattern

• 王家要建房
• Wang wants to build a house.
– Ask Li to setup base(call Li’s function of
setup base)
– Ask Zhao to lay wall bricks (call Zhao’s
function of lay wall bricks)
– Ask Huang to paste wall (call Huang’s
function of paste wall)
• Problem: There are too many direct interactions.
How to cancel so many interactions?
Introductory example to the mediator pattern

• 选举了村长。Then a village head was elected,


and all activities must be organized through the
village head, who has the authority to ask the
villagers to do things.

Zhang

Wang VillageHead Huang

Li Zhao
Introductory example to the mediator pattern

Wang wants to build a house:

• Wangask village head, for building a house


• village head order Li,setup base
• village head order Zhao, lay bicks
• village head order Huang, paste wall
:Zhang

buildHouse() pasteWall()
:Wang :VillageHead
la :Huang
( ) yB
se
a ric
B ks
i ld ()
bu
:Li :Zhao
Introductory example to the mediator pattern

public class VillageHead{


buildHouse{
VillageHead Li.setBase();
Zhao.layBricks()
buildHouse() Huang.pasteWall()
constructRoad()
}
constructRoad{
Li.setBase();
Huang.mixCement()
}
}

Class VillageHead and its Implementation Back


Mediator Pattern

DESCRIPTION
• Generally, OO applications consist of a set of
objects that interact with each other for the
purpose of providing a service.
• This interaction can be direct (point-to-point) as
long as the number of objects referring to each
other directly is very low.
Mediator Pattern

ObjectA ObjectB
Mediator Pattern
• As the number of objects increases, this type of direct
interaction can lead to a complex maze of references
among objects.
A

B H High
coupling
C G
如果要增加一个
新的类,则所有
D F 类的接口均需要
改变
E
Drawbacks of point to point communications
The high coupling of so many objects
a) Results in complex method calls
b) affects the maintainability of the application
(如果你要增加一个新的类,就太麻烦了)
c) greatly reduces the scope for reusing these
objects because of higher couplings

Question: How to overcome the above


problems?
Mediator Pattern
Solution: To reduce the tight coupling among
objects, redesign using star-like form, the
mediator design pattern

A
B H

C Mediator G

D F
E
Logical Diagram of the Mediator Design Pattern
Mediator Pattern

• 问题:怎样设计类图才能实现以上的逻辑
图?

• 回答:Mediator类应该与参与者类(对象
A,B,C,…,H的类)之间有某种形式的关联
,而参与者类之间不应该有关联。
Mediator Pattern
The following class diagram represents the
above logics
Colleague
m -m: Mediator
Mediator +method()
C[ ]: Colleague
+registerColleage(c: Colleague)
+operation() Colleague1 Colleague2
-m: Mediator -m: Mediator
+method() +method()

The mediator pattern with only one mediator class


Mediator Pattern
• 为什么中介者类必须拥有register方法?
• The mediator class must know all the
concrete participate colleagues, and so this
class needs a register method
• The register method can be used to let the
mediator class keep all the participate
objects

• 为什么每个Colleague子类都必须保持中介者类
的引用? On the other hand, each participate
class must keep a reference of the mediator
class, so that it can call the methods in the
mediator class to do something.
Mediator Pattern

m Colleague
Mediator
-m: Mediator
-c[ ]: Colleague +method()
+registerColleage(c: Colleague)
+operation()
Colleague1 Colleague2
ConcreteMediator -m: Mediator -m: Mediator

-c[ ]: Colleague +method() +method()


+registerColleage(c: Colleague)
+operation()

The mediator Pattern


Mediator Pattern

• 该设计类图由两部分组成,一部分是中介者类,
另外一部分是以上的参与者对象。
• 程序的构件说明:
• Mediator:中介者的接口。
• ConcreteMediator:具体的中介者,可以有多个
具体的中介者。
• Colleague:参与者对象接口
• Colleague1, Colleague2:具体的参与者。可
以有多个具体的参与者。
Mediator Pattern

中介者模式的主要思想:解耦
We may use the mediator pattern to reduce the
direct invocations among objects
• The Mediator pattern suggests abstracting all
object interaction details into a separate
class, a Mediator
– The Mediator will keep a reference of each
of the interacting objects
– The Mediator will provide methods to call
the participating objects
Mediator Pattern

• 两个参与者对象之间怎样实现交互?
• The interaction between any two different objects is
routed through the Mediator class.
Ø All objects send their messages to the mediator (call
methods of Mediator)
Ø The mediator then sends messages to the
appropriate objects to implement the application’s
requirements (in the mediator then call methods
every other objects).
Mediator Pattern
1. Object B calls a method
in class mediator.
2. Then object mediator will
A call methods in classes E、
B H F、G.
3. Objects E, F, G may also
call back the methods in
C Mediator G class Mediator
4. Mediator may in turn call
other objects
D F
注:Object B may not know
E which class has been
called

How Objects interact in the Mediator pattern?


Advantages of Mediator Pattern

1. 参与者类重用性变得更好. Moving inter object


dependencies out of individual objects
results in enhanced object reusability.

2. 参与者对象之间的关系可以由中介者子类对象调
节. It becomes easier to alter the behavior of
object inter relationships, by replacing the
mediator with one of its subclasses with
extended or altered functionality.
Advantages of Mediator Pattern

HouseTrader
+register()
+transact()

SaleMediator RentMediator trade() trade()


+register() +register()
+transact() +transact()

trade() trade() trade() trade()

An Example Design in Mediator Pattern


Advantages of Mediator Pattern

Advantages of Mediator pattern (cont):


3. 有利于参与者类的单元测试。Objects can be
unit tested more easily, because objects
do not need to refer to each other directly
4. 有利于参与者类的修改。The low degree of
coupling allows individual classes to be
modified without affecting other classes.
• Disadvantage :
• Using a mediator may compromise
performance

Back
Example of Mediator Pattern

• Example: Hotel-Airline-Tour info system


• See the following class diagram for the Mediator
pattern implementation of collaboration program
for
– Hotel,
– Airline and
– Tour.

• The prototypes of three user interfaces for the


Hotel, Airline and Tour are as below.
Example of Mediator Pattern

Hotel information GUI


Example of Mediator Pattern

Airline information GUI


Example of Mediator Pattern

Tour information GUI


Example of Mediator Pattern

Hotel Flight Tour


-flight Flight -hotel Hotel -hotel Hotel
-tour Tour -tour Tour -flight Flight

+reserveRoom() +reserveTicket() +reserveTour()


+checkIn() +checkIn() +checkIn()
+checkOut() +checkOut() +checkOut()
+notifyAirline() +notifyHotel() +notifyHotel()
+notifyTour() +notifyTour() +notifyFlight()
+display() +display() +display()

Class diagrams
Example of Mediator Pattern
• Objective: When a receptionist inputs
customer information into hotel info GUI,
then the flight info GUI and the tourist info
GUI will show the same information,
including
– customer’s name,
– id number, and
– nationality
• So that all the three companies will share
information, and then to get more possible
customers.
Example of Mediator Pattern
In such a way, all the 3 companies are tightly
coupled as figure below.
Airline
in e (
)
A i rL
if y
not

+notifyAirLine()
t e l()
Ho

+notifyTour()
o t i fy
n
noti
fyTo
u r ()
Hotel n o t if
yH o t
el()

TourCompany
The three objects are tightly coupled
Example of Mediator Pattern

• In order to reduce the close couplings of the 3


objects, we can introduce another object which
is called TourMediator.
• All the concerned transactions among the three
objects will be carried out through the
TourMediator.
Example of Mediator Pattern

Airport

BusinessMediator

Hotel TourCompany

Use mediator to reduce the coupling


TestMediator
Example of
AirlineGUI Mediator
-mdtr TourMediator Pattern
getCusName()
getCusID()
getCusNation()
addCustomer(String cus)
+checkIn()
+checkSafety()
+displayInfoToScreen(text);

BusinessMediator TourGUI
HotelGUI
-mdtr TourMediator
-mdtr TourMediator hotelGui: HotelGUI;
getCusName() airlineGui: AirlineGUI; getCusName()
getCusID() tourGui: TourGUI getCusID()
getCusNation() getCusNation()
addCustomer(String cus) +registerHotelGUI(HotelGUI hg) addCustomer(String cus)
+reserveRoom() +registerAirlineGUI(AirlineGUI ag +findHotel()
+checkIn() +registerTourGUI(TourGUI tg) +checkIn()
+checkOut() +addAllCandidateCus(HOTEL,cusInfo) +checkOut()
+displayInfoToScreen(); +updateAllGuis(String text) displayInfoToScreen();

Class diagram using mediator design pattern


BusinessMediator mediator = new BusinessMediator();
new HotelGUI(mediator);
TestMediator new AirlineGUI(mediator);
new TourGUI(mediator);

AirlineGUI
-mdtr TourMediator
AirlineGUI(mediator)
getCusName()
getCusID()
getCusNation()
addCustomer(String cus)
+checkIn()
+checkSafety()
+displayInfoToScreen(text);

BusinessMediator TourGUI
HotelGUI
-mdtr TourMediator
-mdtr TourMediator hotelGui: HotelGUI;
HotelGUI(mediator) airlineGui: AirlineGUI; TourGUI(mediator);
getCusName() tourGui: TourGUI getCusName()
getCusID() getCusID()
getCusNation() +registerHotelGUI(HotelGUI hg) getCusNation()
addCustomer(String cus) +registerAirlineGUI(AirlineGUI ag addCustomer(String cus)
+reserveRoom() +registerTourGUI(TourGUI tg) +findHotel()
+checkIn() +addAllCandidateCus(HOTEL,cusInfo) +checkIn()
+checkOut() +updateAllGuis(String text) +checkOut()
+displayInfoToScreen(); displayInfoToScreen();
Typical Interactions
BusinessMediator mediator = new BusinessMediator();
new HotelGUI(mediator);
TestMediator new AirlineGUI(mediator);
new TourGUI(mediator);

AirlineGUI
-mdtr TourMediator
getCusName()
getCusID()
getCusNation()
Input: addCustomer(String cus)
Mike Sun +addAllCandidateCus(AIRLINE,
cusInfo)
111666 +displayInfoToScreen(text);
China
BusinessMediator TourGUI
HotelGUI
-mdtr TourMediator
-mdtr TourMediator hotelGui: HotelGUI;
airlineGui: AirlineGUI; getCusName()
getCusName() getCusID()
getCusID() tourGui: TourGUI
getCusNation()
getCusNation() addCustomer(String cus)
addCustomer(String cus) +registerHotelGUI(HotelGUI hg)
addAllCandidateCus(HOTEL, +registerAirlineGUI(AirlineGUI ag +addAllCandidateCus(TOUR,
cusInfo) +registerTourGUI(TourGUI tg) cusInfo)
+addAllCandidateCus()
+displayInfoToScreen(); +updateAllGuis(String text) displayInfoToScreen();

当输入客户信息时候的典型交互
Example of Mediator Pattern
public class BusinessMediator{
private HotelGUI hotelGui;
private AirlineGUI airlineGui;
private TourGUI tourGui;

public void registerHotelGUI(HotelGUI hg) { hotelGui = hg; }


public void registerAirlineGUI(AirlineGUI ag) { airlineGui = ag; }
public void registerTourGUI(TourGUI tg) { tourGui = tg; }

public void updateAllGuis(String option, String text) {


if(option.compareTo(AirlineGUI.AIR)==0) {
hotelGui.displayInfoToScreen(text);
tourGui.displayInfoToScreen(text); }
else if(option.compareTo(HotelGUI.HOTEL)==0){
airlineGui.displayInfoToScreen(text);
tourGui.displayInfoToScreen(text);
}}
Example of Mediator Pattern

public class AirlineGUI extends JFrame {


public AirlineGUI (BusinessMediator bMdtr) {
bMdtr.registerAirlineGUI(this);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals(SUBMIT)) {
setCusName();
String cusInfo = getCusName();

bMediator.updateAllGuis(AIR, cusInfo);
}
}}

Source code for the mediator class


Example of Mediator Pattern

public class HotelGUI extends JFrame {


public HotelGUI (BusinessMediator bMdtr) {
bMdtr.registerAirlineGUI(this);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {

if (ae.getActionCommand().equals(SUBMIT)) {
setCusName();
String cusInfo = getCusName();
bMediator.updateAllGuis(AIR, cusInfo);
}
}}

Source code for the mediator class


Example of Mediator Pattern

public class TestMediator{


private static BusinessMediator mediator;
public static void main(String args[]) {
try{
mediator = new BusinessMediator();
new AirlineGUI(mediator);
new HotelGUI(mediator);
new TourGUI(mediator);

}
catch (Exception ee){
ee. printStackTrace();
}
}
}

Source code for the mediator class Back


Implementation details of the mediator pattern

1. Write a Mediator class


Write a mediator class, and claim private
variables that have types of all objects that
participate in the design of mediator pattern,
for example
• private hotelGui: HotelGUI;
• private airlineGui: AirlineGUI;
• private tourGui: TourGUI
Implementation details of the mediator pattern

2. Write registration method


In the mediator class, write all registration
methods to register all the participating
objects. The participating object types should
be included in the parameters of the
registration methods respectively, for example
• registerHotelGUI(HotelGUI hg)
• registerAirlineGUI(AirlineGUI ag)
• registerTourGUI(TourGUI tg)
Implementation details of the mediator pattern

3.Inside each registration method, assign the


object passed from the parameter to the
corresponding private member. For example,
registerHotelGUI(HotelGUI hg){
hotelGui = hg;
}

In this way, the participating objects have been


“pulled” into the mediator object.
Implementation details of the mediator pattern

• Implementation of the main class


Inside the client
class, an object of the mediator class should
be created
And then the
objects for all the participating classes should
be created with the just-created object
passing in though the parameters.

Back
Software Architectures

Professor
3. Cloud Delivery Models
4. Data Center (数据中心)
5. Comparison of grid computing with cloud
computing
6. Key technologies of cloud computing
Introduction to Cloud Computing
Introduction to Cloud Computing

• 大型互联网企业能力过剩
• Amazon, like most computer networks,
were using as little as 10% of their capacity
at any one time,
• Reason: leave room for occasional spikes.
Introduction to Cloud Computing
• 所以,一些企业看到了商机,出租服务
• Amazon:
• Amazon wanted to provide cloud computing to external
customers, and
• launched Amazon Web Services (AWS) on a utility
computing basis in 2006.

• IBM:
• IBM announced the IBM SmartCloud framework to
support Smarter Planet in 2001.
• Cloud computing is a critical component of the Smarter
Computing foundation.
Introduction to Cloud Computing
• 企业可以将其业务移动到“云端”:
• The term "moving to cloud" also refers to an
organization moving away from a
Øtraditional CAPEX model (buy the dedicated
hardware and depreciate it over a period of
time) 资本支出模式(购买专门的硬件设备,而
很快就贬值了) to
Øthe OPEX model (use a shared cloud
infrastructure and pay as you use it). 运营支出
模式(使用云基础设施,用时才花钱)。
Introduction to Cloud Computing
商业人士看云计算 Cloud Computing
a)Data stored on the cloud
b)Software & services on the cloud - Access via
web browser
c) Accessible from any device
Concept of Cloud Computing
Concept of Cloud Computing
The NIST Definition of Cloud Computing
Cloud computing is a model for enabling
ØUbiquitous (无处不在的),
Øconvenient, (方便的)
Øon-demand (按照需求的)
network access to a shared pool of configurable
computing resources,e.g.,
Ønetworks,
Øservers,
Østorage,
Øapplications, and
Øservices
that can be rapidly provisioned and released with
minimal management effort or service provider
interaction.
Concept of Cloud Computing
• 云计算应该具有的5个基本特点:
1)按需自我服务 On-demand self-service.
• A consumer can unilaterally(单方面)provision
computing capabilities, such as
• server time and (服务器时间)
• network storage, (网络存储)
as needed automatically without requiring
human interaction with each service’s
provider.
Concept of Cloud Computing

2)宽网访问 Broad network access.


•Capabilities are available over the network and
accessed through standard mechanisms that
promote use by heterogeneous (多样的) thin
or thick client platforms,e.g.,
Ømobile phones;(手机)
Ølaptops, and;(笔记本电脑)
ØPDAs. (个人数字助理,集中了电话、传真、
网络等功能)
Concept of Cloud Computing
3)资源池Resource pooling.
•The provider’s computing resources are pooled to
serve multiple consumers using a multi-tenant model,
with different physical and virtual resources
dynamically assigned according to consumer
demand.
– Location independence:
• 客户不知道自己的资源存在哪里 the customer
generally doesn’t know the exact location of the
provided resources but
• 客户可以指定资源存放地区 may be able to specify
location at a higher level of abstraction (e.g., country,
state, or data center).
Concept of Cloud Computing

4)快速弹性Rapid elasticity.
•Capabilities can be rapidly and elastically
provisioned, in some cases automatically, to
Øquickly scale out(快速扩展), and
Ørapidly released (快速释放)
Øquickly scale in(快速收缩).

•To the consumer, the capabilities available for


provisioning often appear to be unlimited and can
be purchased in any quantity at any time.
Concept of Cloud Computing
5)服务度量 Measured Service.
•Cloud systems automatically control and optimize
resource use by leveraging a metering capability
(计量能力) at some level of abstraction appropriate
to the type of service e.g.,
Ø storage; 通过计量
Ø processing; 控制、优
Ø bandwidth, and; 化资源
Ø active user accounts.
•Resource usage can be monitored, controlled, and
reported, providing transparency for both the
provider and consumer of the utilized service.
Concept of Cloud Computing

容易理解的“云”的定义
• 云是互联网服务,是复杂基础架构、应用、数据、
异构平台的抽象
• 云计算是云提供商提供的租借计算服务,可使外部
客户租借他们集群进行计算
– Amazon EC2: virtual machines at 10¢/hour,
billed hourly
– Amazon S3: storage at 15¢/GB/month
Concept of Cloud Computing
服务 每一层管理的资源 实例
Business Applications Google Apps,
Web Services, Multimedia Facebook,
软件即服务 (SaaS) YouTube
Applications Salesforce.com

Runtimes, Google
Operating System, AppEngine,
平台即服务(PaaS) Database Microsoft Azure
Platform
Computing (VM), Amazon EC2,
基础设施即服务 Storage Eucalyptus
(IaaS) OpenNEbula
Infrastructure

Server, Network
硬件: Data Centers
服务器、网络 Hardware
SaaS 个人用户,
CRM, Email, visual desktop, 公司用户
communication, games…

PaaS
Execution runtime, database,
web server, 公司用户
development tools…

IaaS
Virtual machines, servers,
storage, 公司用户
load balancers, network, etc,…

云计算架构图
Cloud Delivery Models
(Service Models)
(云服务提供模式)
Cloud Delivery Models
• Software as a Service (SaaS)(软件即服务交付模型)
– Use provider’s applications over a network
– On-demand applications
– E.g. GMail, Google map, 百度地图
• Platform as a Service (PaaS) (平台即服务交付模型)
– Deploy customer-created applications to a cloud
– On-demand application-hosting environment
– E.g. Google AppEngine, Salesforce.com, Windows
Azure, Amazon
• Infrastructure as a Service (IaaS) (基础设施即服务交付模
型)
– Rent processing, storage, network capacity, and other
fundamental computing resources
– On-demand servers
– Amazon EC2, VMWare vCloud
Cloud Delivery Models

= Managed for You IaaS PaaS SaaS

提供并
提供并 且管理
且管理 的条目
提供并 的条目
且管理
的条目

云计算对各种出租服务的配置
Cloud Delivery Models

SaaS (软件即服务)
• SaaS is a software delivery model in which
software and associated data are centrally
hosted on the cloud.(软件与数据都在云端)

• SaaS is typically accessed by users using a thin


client via a web browser.(是将软件和数据部署于
云端的一种软件交付模式,客户通常通过浏览器
使用软件)
Cloud Delivery Models

• SaaS has become a common delivery model for


most business applications, including
– accounting (会计业务);
– Invoicing(货品计价);
– CRM(客户关系管理);
– MIS(管理信息系统);
– ERP(企业资源计划);
– HRM(人力资源管理), etc.
Cloud Delivery Models
PaaS (平台即服务)
• PaaS is a category of cloud computing services
that provide a computing platform and a solution
stack as a service. (将计算平台及方案栈作为服务)

• PaaS模型提供了计算平台
• In the PaaS model, cloud providers deliver a
computing platform and/or solution stack typically
including
Ø operating system, 操作系统
Ø programming language execution environment,运行环境
Ø database 数据库
Ø web server Web服务器
Cloud Delivery Models
IaaS(基础设施即服务)
• In this most basic cloud service model, cloud providers
offer
Øcomputers – as physical or more often as virtual
machines, 虚拟机
Øraw (block) storage,块存储
Øfirewalls,防火墙
Øload balancers, and负载均衡
Ønetworks.网络

• IaaS providers supply these resources on demand


from their large pools installed in data centers. (按需提
供)
Cloud Delivery Models

• In this model, it is the cloud user who is


responsible for
Øinstalling, (自行安装)
Øpatching and (自行修补)
Ømaintaining (自行维护)
the operating systems and application
software. 操作系统和应用程序

• Cloud providers typically bill IaaS services on a


utility computing basis, that is, cost will reflect
the amount of resources allocated and
consumed. (提供商根据资源使用情况计费)
Cloud Delivery Models

Example: Google
• Google云计算应用实例
Data Center (数据中心)
Data Center
• 数据中心是一整套复杂的设施,它包含了:
Ø计算机系统和其它与之配套的设备(例如通信和存储
系统;
Ø冗余电源;
Ø数据通信连接;
Ø环境控制设备(例如空调防火设备);
Ø各种安全装置。

数据中心选址应该考虑的
因素:
Ø 地理位置
Ø 电力能源供应
Ø 通讯基础设施
Data Center

• 数据中心规模(2012年估计)
– Google服务器数量:约100万台(2012年)
– Amazon服务器数量:约45万台(2012年)
– Microsoft服务器数量:约21万台(2008年)
– Intel服务器数量:约10万台(2011年)
– Akamai服务器数量:约10.5万台(2012年3月)
– Facebook服务器数量:约6万台(2009年)
– Taobao CDN服务器数量:约4000台(2012年)
Comparison of Grid Computing
with Cloud Computing
Comparison of Grid Computing with Cloud Computing

Grid Computing (网格计算)


• 解决大规模的计算问题
• To solve large-scale computation problems
– breaking large data sets down into many smaller
ones
– modeling a parallel division of labor
• 网格计算为诸多挑战性的问题提供了解决途径
• Grids offer a way to solve Grand Challenge problems
such as:
– protein folding (蛋白质折叠)
– financial modelling (经济与金融建模)
– earthquake simulation (地震模拟)
– climate/weather modelling (气候/天气建模)
– astronomical searching (天体搜索)
Comparison of Grid Computing with Cloud Computing

网格计算 云计算

•异构资源 •同构资源
•不同机构 •单一机构
•虚拟组织 •虚拟机
•科学计算为主 •数据处理为主
•标准化 •尚无标准
•科学界 •商业社会
Key Technologies of Cloud
Computing
Key Technologies of Cloud Computing

关键技术1:Virtualization (虚拟化)
• Virtualization is the creation of a virtual (rather
than actual) version of something, such as a
– hardware platform, 硬件平台
– operating system, 操作系统
– storage device, or 存储设备
– network resources. 网络资源
Key Technologies of Cloud Computing

• Types of Virtualization
– Infrastructure Virtualization (基础设施虚拟化)
• CPU、内存、设备/IO、网络
– System Virtualization (系统虚拟化)
• 虚拟机,如Xen, VMware, VirtualBox
– Software Virtualization (应用虚拟化)
• 应用、语言,如JVM
Key Technologies of Cloud Computing
• 虚拟化节省IT开支&提高资源利用率
需要购买8台服务器
SQL SQL SQL SQL
经过虚拟化只需购买2台服务器
SQL SQL SQL SQL SQL SQL SQL SQL

SQL SQL SQL SQL

8 servers 2 servers
16 processors / licenses 4 processors / licenses

$600K
$596K >70% cost $600K
$500K
SA
reduction $500K
$400K 16 Enterprise $400K
$300K Edition $300K
$200K licenses $200K $158K
SA
$100K $100K 4 licenses
8 servers
2 servers
Key Technologies of Cloud Computing
关键技术2:大规模分布式数据存储(big data)
• 大数据概念:Big data refers to data sets whose size
is beyond the ability of commonly used software tools
to capture, manage, and process the data within a
tolerable elapsed time. (数据量巨大、传统软件数据处
理工具无法在可接受的时间内处理完毕)

• 问题:
• It’s hard to work with it using relational databases and
desktop statistics/visualization packages,
• require “massively parallel software running on hug
number of servers”.(需要数以千计的服务器平行处理)
Key Technologies of Cloud Computing

大规模分布式数据存储实例: GFS
• Google文件系统(Google File System,GFS)
是构建在廉价的服务器之上的大型分布式系统。
它将服务器故障视为正常现象,通过软件的方式
自动容错。保证了系统可靠性、可用性,大大减
少了系统的成本。
• GFS是Google云存储的基石。另外,Google大规
模批处理系统MapReduce也需要利用GFS作为海
量数据的输入输出。
Key Technologies of Cloud Computing
• GFS架构

– 将文件划分为若干块(Chunk)存储,每块64M。服务器
给每块分配一个不变的、全球唯一的64位的块句柄对
它进行标识。
– 单一Master, 多个ChunkServer,通过单个master来协
调数据访问、元数据(描述数据及其环境的数据)存

– ChunkServer把块作为linux文件保存在本地硬盘上,
并根据指定的块句柄和字节范围来读写块数据。通过
冗余提高可靠性:每个数据块至少在3个ChunkServer
上冗余
– 客户端跟Master交互进行元数据操作,但是所有的数
据操作的通讯都是直接和ChunkServer进行的。
负责数据
File 1
块存储 Trunk 1
直接访问Trunk服务器
Trunk File 1
Server 1 Trunk 2
File 2
Trunk 1

File 1

Trunk Trunk 2

映射 Trunk File 1
App Master Server 2 Trunk 1
File 2
协调数据访问、 负责数据 Trunk 2
元数据存储 块存储

File 1
Trunk 2
直接访问Trunk服务器 Trunk File 2
Server 3 Trunk 1

负责数据 File 2
Trunk 2
GFS架构图 块存储
Key Technologies of Cloud Computing

• Master节点功能
– 存储元数据
– 文件系统目录管理与加锁
– 与ChunkServer进行周期性通信
• 发送指令,搜集状态,跟踪数据块的完好性
– 数据块创建、复制及负载均衡
• 对ChunkServer的空间使用和访问速度进行
负载均衡,平滑数据存储和访问请求的负载
• 对数据块进行复制、分散到ChunkServer中
Key Technologies of Cloud Computing

• GFS特点
– 采用中心服务器模式
• 可以方便地增加Chunk Server
• Master掌握系统内所有Chunk Server的情况,方便
进行负载均衡
• 不存在元数据的一致性问题
– 不缓存数据(的原因)
• GFS的文件操作大部分是流式读写,不存在大量的重
复读写,使用Cache对性能提高不大
• Chunk Server上的数据存取使用本地文件系统,如
果某个Chunk读取频繁,文件系统具有Cache
– 在用户态下实现直接利用Chunk Server的文件系统存
取Chunk,实现简单
Key Technologies of Cloud Computing
关键技术3:Mass Data Processing(海量数据处理)
• 待处理数据量巨大(PB级),只有分布在成百上千个
节点上并行计算才能在可接受的时间内完成,例如:
– Index construction for Google Search
– Spam detection for Yahoo! Mail

1K = 2的10次方 Byte 1EB = 2的60次方 Byte

1M = 2的20次方 Byte 1ZB = 2的70次方 Byte

1G = 2的30次方 Byte 1YB = 2的80次方 Byte

1TB = 2的40次方 Byte 1DB = 2的90次方 Byte

1PB = 2的50次方 Byte 1NB = 2的100次方Byte


Key Technologies of Cloud Computing

• 如何进行并行分布式计算(有一些算法)
• MapReduce is
– a programming model and
– an associated implementation for processing
and generating large datasets
– It was introduced by Jeffery Dean in 2004.
Key Technologies of Cloud Computing

MapReduce Statistics
• 对1000台计算机上的1TB数据进行排序仅需要68s
• 对4000台计算机上的1PB数据进行排序处理仅需要
6小时2分钟
• 在08年1月份,Google MapReduce平均每天的数
据处理量约20PB
Key Technologies of Cloud Computing
关键技术4:多租户架构 Multi-tenant
Architecture (MTA)

• 多租户概念 Multi-tenancy refers to a principle in


software architecture where a single instance of
the software runs on a server, serving multiple
client organizations (tenants). (单个应用实例服务
多个租户)

• 多租户是SaaS中的关键技术
Key Technologies of Cloud Computing

• 租户(Tenent)与用户(user)的区别?
• 【例子】: 基于SaaS的网上电影院订票系统
– 登录网上订票系统订票的影迷是系统的一类用

– 租用该系统的电影院的是租户
• 电影院内部员工通过系统进行影讯发布和售
票,他们是租户内的用户
Key Technologies of Cloud Computing
SaaS 的4层成熟度模型 4-Level Maturity Model of SaaS
Tenant 1 Tenant 2 Tenant 3 Tenant 1 Tenant 2 Tenant 3

(a)Ad-Hoc/Custom (b) Configurable

Tenant 1 Tenant 2 Tenant 3


Tenant 1 Tenant 2 Tenant 3

Load Balancer

(c) Configurable, (d) Scalable, Configurable,


Multi-Tenant-Efficient Multi-Tenant-Efficient
2022-11-3 48
From Tsai Wei-Tek
Key Technologies of Cloud Computing

Level 1 - Ad-Hoc / Custom (专门的、定制的)


• Each customer has its own customized version of
the hosted application and runs its own instance of
the application on the host's servers.

每个租户都有为
其专门定制的应用程序版本。
例如财务系统定制版本:
1)清华大学财务系统
2)北京大学财务管理系统
3)哈工大财务系统
2022-11-3 49
Key Technologies of Cloud Computing

Level 2 – Configurable (可配置的)


• Greater program flexibility through configurable
metadata, so that many customers can use separate
instances of the same application code.

通过配置,可以
使得许多租户运
行同一个应用程
序的不同的实例。

2022-11-3 50
Key Technologies of Cloud Computing
Level 3 - Configurable, Multi-Tenant-Efficient
可配置-多租户-高效率
• Adds multi-tenancy so that a single program
instance serves all customers.

增加多租户机制,使得
所有的租户运行同一个
应用程序的同一个实例。

问题:怎样区别租户?
难度比较大

2022-11-3 51
Key Technologies of Cloud Computing
Level 4 - Scalable, Configurable, Multi-Tenant-Efficient
可伸缩的,可配置的,多用户的,高效的
• Adds scalability through a multi-tier architecture supporting
a load-balanced farm of identical application instances,
running on a variable number of servers.

增加了可伸缩性,
使得所有的租户运
行同一个应用程序
的同一个实例,运
行在许多服务器上。
Ø快速扩展
Ø快速释放
Ø快速收缩.
2022-11-3 52
Key Technologies of Cloud Computing

关键技术5:多租户架构的资源隔离模式
(Resource Isolation Patterns of Data Tier in MTA)

• 每个租户都有其独立数据库 Separate databases (SD)


– Each tenant has its own database
– Other resources (CPU, storage, code) shared
– Easy to extend data model and recover
– Expensive in maintaining many copies of DBs

对于云计算
提供商来讲
费用太高
2022-11-3 53
Key Technologies of Cloud Computing

Resource Isolation Patterns of Data Tier in MTA


• 所有租户共享同一个数据库,但是各个租户有其独立
数据模式 (Shared database separate schemas (SDSS))
– Each tenant has its own database schemas
– Easy to implement and extend data model

Ø 每个租户都有其
独立的数据模式;
Ø 容易实现和扩
展数据模型

2022-11-3 54
Key Technologies of Cloud Computing
Resource Isolation Patterns of Data Tier in MTA
• 所有租户共享共享数据库与数据模式 (Shared database shared schemas
(SDSHS))
– All tenants share the same schemas, easy to
maintain
– Most complex due to security reasons
– Hard to restore after failures

Ø 所有租户共享数据
模式与数据库;
Ø 实现起来比较困难
Ø 失败以后不容易恢复

2022-11-3 55
Students Stop Here

The remaining PPTs are used for students


who are interested in cloud computing
Mainstream Platforms for Cloud
Computing
Mainstream Platforms for Cloud Computing

Amazon云计算平台AWS
• IaaS基础设施产品
• 弹性计算云EC2
– EC2 is a central part of AWS. EC2 allows users to rent
virtual computers on which to run their own computer
applications.
– EC2 allows scalable deployment of applications by
providing a Web service through which a user can boot
an Amazon Machine Image to create a virtual machine,
containing any software desired.
– A user can create, launch, and terminate server
instances as needed, paying by the hour for active
servers.
• Small (Default) $0.10 per hour $0.125 per hour
• All Data Transfer $0.10 per GB
Mainstream Platforms for Cloud Computing

Amazon云计算平台AWS
PaaS平台产品
– Amazon S3 (简单存储服务S3 ) 提供一个简
明的 Web 服务界面,用户可通过它随时在
Web上的任何位置存储和检索的任意大小的数
据。 此服务让所有开发人员都能访问同一个具
备高扩展性、可靠性、安全性和快速价廉的基
础设施。 此服务的目标是为开发人员带来最多
的利益。
• $0.150 per GB – first 50 TB/month of storage used
• $0.100 per GB – all data transfer in
• $0.01 per 1,000 PUT, COPY, POST, or LIST
requests
Mainstream Platforms for Cloud Computing

Amazon云计算平台AWS
PaaS平台产品
– 简单数据库服务Simple DB
– 简单队列服务SQS
– 弹性MapReduce
– 内容推送服务CloudFront
Mainstream Platforms for Cloud Computing

Amazon云计算平台AWS
• SaaS产品
– 电子商务服务DevPay
– 灵活支付服务FPS
Mainstream Platforms for Cloud Computing

Google云计算平台
• Google云计算平台技术架构
– 文件存储:Google Distributed File
System,GFS
– 并行数据处理:MapReduce
– 分布式锁:Chubby
– 结构化数据表:BigTable
Mainstream Platforms for Cloud Computing

• Google App Engine (PaaS)


• App Engine is a platform as a service that uses familiar
technologies to build and host applications on the same
infrastructure used at Google.
• Enable developer productivity:We provide you with
familiar development tools that allow you to build, test
and deploy quickly
• Scale automatically:Whether you get huge traffic
spikes or have lower traffic periods, App Engine scales
your instances up and down automatically.
– 500MB of storage
– up to 5 million page views a month
– 10 applications per developer account
– Language: Python、Java
Mainstream Platforms for Cloud Computing

• Google Applications (SaaS)


– 谷歌文件:Google Docs
– 谷歌邮件:Google Mail
– 谷歌日历:Google Calendar
– 谷歌地图:Google map
–…
Mainstream Platforms for Cloud Computing

微软云计算平台Azure platform as service


Mainstream Platforms for Cloud Computing

Salesforce.com云计算平台
Mainstream Platforms for Cloud Computing

Salesforce.com云计算平台
• Database Server: Oracle RAC EE, Dell, Sun
• Clustering: SunCluster
• Web Site and Application Server: Dell, Resin
• Search Server: Jakarta Lucene
• Storage Management: Hitachi Data Systems, Sun
• Backup Software: Veritas/RMAN
• Operating Systems
– Sun Solaris
– Redhat Linux
Mainstream Platforms for Cloud Computing
开源云计算平台Hadoop
• Open Source Apache Project
• Hadoop Core includes:
– Distributed File System - distributes data
– Map/Reduce - distributes application
• Written in Java
• Runs on
– Linux, Mac OS/X, Windows, and Solaris
– Commodity hardware

Hadoop云计算系统 对应Google云计算系统
Hadoop HDFS Google GFS
Hadoop MapReduce Google MapReduce
Hadoop HBase Google Bigtable
Hadoop ZooKeeper Google Chubby
Mainstream Platforms for Cloud Computing
开源云计算集成平台Ezilla
• Ezilla (Easy La) helps users quickly and easily build their own
private cloud!
• Ezilla integrates storage, networking, and computing resources
under a cloud and allows cloud service providers to swiftly
deploy cloud service environments that are built on a user-
friendly, web-based interface.
• Integrated Open source resources
– Linux (开源OS: hosted machine OS & Virtual machine OS)
– OpenNEbula (类似EC2的开源实现)
– EyeOS (开源云操作系统)
– Xen (开源虚拟机)
Try It!

http://ezilla.info/
结束

2022年11月3日
Software Architecture
软件体系结构
Contents:
B2B Electronic Commerce

• B2B (Business-To-Business)
• B2B definition: A transaction that occurs
between two companies.

• B2B electronic commerce typically takes the


form of automated processes between
trading partners.
B2B Electronic Commerce

. Suppose that Intel


sells Micro processor to Dell

EAI EAI

Company 1 Bank Company 2


B2B Electronic Commerce

EAI
EAI
EAI

EAI EAI EAI

Use EAI to integrate multiple applications that


were independently developed,
B2B Electronic Commerce

• Definition: The process of integrating multiple


applications that were
Ø 1)independently developed,
Ø 2)may use incompatible technology, and
Ø 3)remain independently managed.

• By this definition, EAI would include:


1)Business Process Integration(商业过程集成)
2)Enterprise Information Integration(企业信息集
成)
Disadvantages of B2B
SOA架构引言

• 互联网上运行的电子商务应用系统有很多个人用
户,例如电子商务平台淘宝,物流公司,网站,
如下图所示。

个人用户通过登
录网站,进行购 淘宝
买商品的交易。
SOA架构引言

淘宝的业务员们,作为个人用户通过登录物流网
站,进行预定车队的业务。

物流业
务网站

淘宝业务员
SOA架构引言

• 问题:淘宝网站电子交易系统是否可以和物流业
务网站,直接进行交易?

淘宝电子 物流系统
交易系统
SOA架构引言

• 如果可以,怎样做?
接口:
接口:
formLogistics(
getGoodsList():
<dest, pieces>:
ArrayList String[][] )

淘宝电子
物流系统
交易系统

淘宝电子交易系统调用物流系统的接口,组织物流;
或者物流系统调用淘宝电子交易系统获得当日订单,
然后帮助组织物流。
Why do we Want SOA?
We want our application to execute business logic
in many other systems, often dynamically bound
to me

某种业务

Server
动态绑定
动态提供服务
Servers

ØB2B is not enough


Ø3-tire C/S architecture is not enough
Ø需要一个新架构- SOA 架构
空中加油机-采用动态绑定的方式加油
: A service-oriented architecture
(SOA) is the underlying structure supporting
communications between services.
Ø A service is defined as a unit of work to be performed
on behalf of some computing entity, such as a program
(例如:天气预报服务).
Ø SOA defines how two computing entities (计算实体)
such as programs, interact in such a way as to enable
one entity to perform a unit of work on behalf of
another entity.
SOA Principle

a) SOA separates the service‘s implementation


from its interface SOA将服务的接口与实现分
离开
Service consumers view a service simply as
an endpoint that supports a particular
request format or contract 服务消费者将服务
视为支持特定的请求格式或合同的 终点
SOA Principle

interface

A service consumer are not concerned with


how the services are actually done.
SOA Characteristics
SOA的特点
a) Services are discoverable and dynamically
bound 服务可以被发现,并且可以动态绑定.
b) Services are self-contained and modular. 服务
是自我包含的并且是模块化的
c) Services are loosely coupled 服务是松耦合的
d) Services have a network-addressable
interface 服务带有网络可寻址的接口
e) Services are location-transparent 服务是地址
透明的
f) Services can be chained together to form
more complex functionality 服务可以被串在一
起形成更复杂的功能(旅游-机场-酒店)
运输公司1
业务系统
运输公司2
业务系统
物流公司
配车系统 运输公司3
业务系统

运输公司4
动态绑定并且 业务系统
自动进行交易

服务可以被发现,并且可以动态绑定
SOA Principle
Example:TV station uses services provided
by the Weather system

• The TV system uses the weather forecasting functions


from the weather system.
• The TV system only knows the interface that describes
the services provided by the weather system and
doesn’t care how the functionalities are implemented
SOA Architecture and Working Mechanism

Find
Bind and
execute Contract

Register 包含很多服务提
供者目录

The “Find-bind-execute" Paradigm


SOA Architecture and Working Mechanism
SOA Entities

• SOA的5个实体
• SOA consists of the following 5 entities
configured together to support the find,
bind, and execute paradigm.
SOA Entities

Service Consumer (服务消费者)


• 定义:The service consumer is an application,
service, or some other type of software
module that requires a service
• How Service Consumer works?
a) The service consumer locates the service in
the registry, binds to the service over a
transport, and execute the service function
b) The service consumer executes the service
by sending it a request formatted according
to the contract
SOA Entities

Service Provider (服务提供者)


• 定义:The service provider is the service, the
network-addressable entity that accepts and
executes requests from consumers. It is a
software system that executes the service
request.
• How Service Provider Works?
The service provider publishes its contract in
the registry for access by service consumers.
SOA Entities
3. Service Registry (服务注册)
• A service registry is a network-based directory
that contains available services.
• A service registry accepts and stores contracts
from
Ø -service providers and
provides those contracts to
Ø -interested service consumers.

Contract Contract
Service Service Service
Provider Registry Consumer

Contract Contract
SOA Entities

4. Service Contract (服务合同)


• A contract specifies the format of
– 1) the request (请求格式)
– 2) response from the service (反馈格式)
SOA Entities
5. Service Proxy (服务代理)
a) The service provider supplies a service
proxy to the service consumer 服务提供者给服
务消费者一个代理
b) The service consumer executes the request
by calling an API function on the proxy.
c) The service proxy finds a contract and a
reference to the service provider in the registry.
d) It then formats the request message and
executes the request on behalf of the
consumer.
SOA Entities (SOA实体)

2. 获得格式 Contract

Implementation Service 1. 发送proxy


code proxy

3. 按照格式,发
送服务请求

Consumer 给Provider发送请求的过程
What is Web Services?

• Web services的定义
• Web services are Web-based enterprise
applications that use
Ø 1) open,
Ø 2) XML-based standards and transport
Ø protocols to exchange data with calling
Ø clients.

: Web services implements concepts of


SOA, they do not implement all of them.
ØJava supports Web services
Web Services

They do not
currently support the notion of a contract
lease).

• 如果知道了服务地址与合同,服务消费者直接
执行Web services
• Service consumers can execute Web services
directly if they know the service‘s address and
contract In such case, they do not have to go
to the registry to obtain this information.
Basic Web Services
描述和发现服务 UDDI

Points to
UDDI description
Registry

Points to
service
1)Finds
Service
发现服务

SOAP
2)Invokes with
XML Messages
调用服务
. WSDL:
服务地址
服务操作
• UDDI: Enterprise Universal Description,
Discovery, and Integration (UDDI) Services
• Enterprise UDDI Services helps companies
organize and catalog Web services and
other programmatic resources.
SOAP

• SOAP stands for Simple Object Access


Protocol (简单对象访问)
• SOAP is a simple XML-based protocol to let
applications exchange information over HTTP.
(使得许多应用之间利用HTTP协议传递信息)
J2EE Supports Web Services
Java APIs
Description
for XML
JAXP Java API for XML Parsing

JAXB Java API for XML Data Binding

JAX-RPC Java API for XML Remote Procedure Call

SAAJ SOAP API for Attachments in Java

JAXR Java API for XML Registries

EJB 2.1 Stateless Session EJB Endpoint Model

JSR 109 Web Services Deployment Model

Java EE 5 application server


Project GlassFish
In July 2006, Project GlassFish published
• It is a new open-source technology
• It exposes all of the Java web services
technologies at the java.net site for community
development.
• It finds a new way for developers to gain
access to the latest versions of web services
and XML technologies.
• It also replaces our previous release vehicle
for providing new web services and XML
developer tools between releases of the Sun
Java System Application Server, the Java Web
Services Developer Pack.
Why use GlassFish?
• The GlassFish implements an open source
Java EE 5 application server.
• GlassFish is a robust, commercial, production
quality, compatible application server that is
free for development, deployment, and
redistribution.
• GlassFish is Production Quality, has very Good
Performance and is scalable
1. Client-server Architecture

Client/Server Architecture
2.

P2P Architecture
3. Grid Computing Architecture

2 3
1. Main cluster server divides
Tasks into smaller subtasks 2 3
and parcel them to local
cluster servers
1
1
3
3
4 3
1 1
3
Database farm

2 3 4. Main cluster server aggregates complete


tasks and send data back to the dadabase
2 3
farm

2. local cluster servers find


available processing power 3. local cluster servers gather completed tasks from
on local PCs and local PCs and send data back to Main cluster
distributes subtasks into servers
those PCs
4.Cloud computing

大众用户

SaaS
公司租户 CRM, Email, visual desktop,
communication, games…

PaaS
Execution runtime, database, web server,
development tools…

IaaS
Virtual machines, servers, storage,
load balancers, network, etc,…
5. SOA Architecture

Server

Servers

SOA Architecture
Find
Bind and
execute Contract

Register 包含很多服务提
供者目录

The “Find-bind-execute" Paradigm

You might also like