哈工大设计模式课件(孙玉山)
哈工大设计模式课件(孙玉山)
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
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
Java EE Architecture
Introduction to Software Architecture
其它参考书与材料(Reference books)
作业与项目
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
Statement
5 6
A software component
C D can be executed only if
it gets the control
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 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
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
Memory
access
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.parse(file, lines);
shifter.setup(lines);
alphabetizer.alpha(shifter);
output.print(alphabetizer);
}
lines
file
shifter.setup(lines);
alphabetizer.alpha(shifter);
alphabetizer
output.print(alphabetizer); Screen
– Dependency relation(依赖关系)
表现为类B作为参数被类A某个方法使用
Class Relations
Employee String
-name: String
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
Person Car
Return
SortStrategy
US cars
USCar
+run()
+break()
+accelerate
+stop()
+getInstructions()
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
Return
Java Interface( )
}
Java Interface( )
+deposit()
+withdraw()
+transfer()
, an interface can
define a set of related functions for some special
use
Java Interface( )
Account act
if(usrChoice == 1)
act = new
if(usrChoice == 2)
act = new Savings
if(usrChoice == 3)
act = new Online
Java Interface( )
: from Java API
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,
Example of interface
contamination -companyName: String
-companyAddr: String
-trade:
-amount: double
-taxRate: double
-trade: Trade -employeeName: String
-employeeNum: String
-salary: double
- c o m p a n y :
Company +computeTax(): void
Dependence
direction
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
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
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
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
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
分叉 合并
3. Pipes and Filters architecture
Example 6. 如下的Unix命令组成一个管道/过
滤器程序,将in.txt文件的包含“Heroin”的行
进
行排序,然后将结果输出到out.txt文件中。
以上命令行的管道/过滤器结构图如下。
in.txt
Cat
Grep Sort
Grep负责在文件in.txt中搜索包含 将上游管道来的
表达式“cocaine”的所有的行,
out.txt
行进行排序,以后
并且将它们输出到下游管道。 写到out.txt中
3. Pipes and Filters architecture
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
• 例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
设计逻辑
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
阀门 加热器
Set
point:
25 oC
4. Process-control Paradigms
software
software
4. Process-control Paradigms
4. Process-control Paradigms
•
4. Process-control Paradigms
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
2
3
Introduction to Factory Method Pattern
4
Introduction to Factory Method Pattern
Client
obCar: Car
Main() Car
+buyCar()
+buyParts()
5
Introduction to Factory Method Pattern
6
Introduction to Factory Method Pattern
Client Car
obCar: Car +buyCar()
Main() +buyParts()
obCar Lincoln(m);
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
14
Introduction to Factory Method Pattern
.
(隐藏初始对象的细节)
The factory method also implements any
special mechanisms required to instantiate the
selected class.
– This is possible
15
Introduction to Factory Method Pattern
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
21
可以传递参
数给工厂类
Creator.factory(p)
仅仅负责创建对象
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;
28
public class Collision implements
AutoInsurance {
private String 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()
<<create>>
<<create>>
38
Example of Auto Insurance Policies
汽车保险的例子
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
汽车保险的例子
43
Example of Auto Insurance Policies
汽车保险的例子
45
Example of Auto Insurance Policies
汽车保险的例子
48
Example of Auto Insurance Policies
汽车保险的例子
49
Example of Auto Insurance Policies
汽车保险的例子
50
Example of Auto Insurance Policies
汽车保险的例子
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
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.
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.
1)传递参数p,请求创建对象c
将参数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
Professor:
Yushan (Michael) Sun
Fall 2015
Lecture 3. Case Study on Dataflow System
p1
cdefg p1
cdefg p1
cdefg p1
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
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
: 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
Inactive
fast
State Machine
for Toggle
Wheel rotation
Active/inactive toggle of the system
Control
Unit Engine
Event Table Desired speed
for Set Speed
Point sensor
问题:
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.
Waveform Clipped
S S Trace trace
Trace
Waveform Measurement
Times
S S W T T
Couple Acquire To-XY Clip
Trace
Waveform
Times
2)a.
工厂方法模式-汽车保险的例子
1)获得产品
对象a
2)调用方法
a.
+factory: Product +Operation()
<<create>> <<create>>
导致使用抽象工厂模式的例子
导致使用抽象工厂模式的例子
+factory: Shoes
+factory: Suit
+factory: Shirt
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.
+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
<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
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
• 假设我们计划一款格斗类游戏软件.玩家与敌方士
兵以及怪兽进行战斗。
• 为了适应不同等级玩家的需要,游戏特地安排了
三个难度级别:
–初等级别:敌方士兵反应迟钝,怪兽步履缓慢,即便是
初学者也能够很轻松地取胜
–中间级别:敌方士兵反应适度,怪兽步履速度中等,中
级玩家有可能取胜
–高难级别: 敌方士兵反映敏捷,怪兽狰狞狡诈,就算
是高级玩家也难逃被击毙的厄运。
请应用抽象工厂模式进行设计。
格斗类游戏软件
• 在具体实现时可以先设计两个抽象产品类Fighter和
Monster,用来代表士兵和怪兽。
• Fighter: SlowFighter, MedFighter, SuperFighter
• Monster: SlowMonster, MedMonster, SuperMonster
• 注意: 用户有三种选择:初级,中级,高级
• 初级: SlowFighter, SlowMonster
• 中级: MedFighter, MedMonster
• 高级: SuperFighter, SuperMonster
格斗类游戏软件
• 为了保证这种一致性,程序员在编码时必须非常
小心,否则稍有疏忽,那些正在痛击
SlowFighter的初级游戏者一转身撞上一个
SuperMonster,肯定会败得一塌糊涂。
• 抽象工厂模式可以很好地解决这一问题,设计抽
象工厂 然后再根据不同的
难度级别依次构造 和
• 三个具体工厂,并由它们负责按照当前游戏策略
的要求去生成具体的士兵和怪兽。
Back
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:
Proc1 中石油=15元
Pr
Proc2 中石化=10元 oc
ed
Evt1
Pr 1
oc
中国铝业
Pr ed
Evt2 oc 2
ed
中国航空 Ev 3
t1
Ev
t2
我注册
我注册
调用 调用
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
<<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.
通知观察者的两种策略:
• 【注】观察者模式有许多变形
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)
都已经实现了。
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
or
and
4. Observerble/Observer example
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>);
注意:这里没有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
//此处省略了图形界面生成代码
public void update(Observable subject, Object arg) {
String t = (String) arg; //用户输入的温度数值
//参数subject代表被观察者TemperatureGUI对象
TemperatureGUI tg = (TemperatureGUI)subject;
//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
7
Introduction to Adapter Pattern
220 volt
electric
8
Introduction to Adapter Pattern
220 v
electric
• 在软件设计中,我们也经常会遇到类似的接
口不一致的问题
10
Introduction to Adapter Pattern
200
300 11
Introduction to Adapter Pattern
我们希望以如下的方式声明椭圆
b 我们需要
a 这样声明
(cx, cy) 一个椭圆
即可创建所需的按照:
椭圆中心,长班轴,短半轴
方式声明的椭圆
14
Introduction to Adapter Pattern
Adaptee
Operation1:void
16
Introduction to Adapter Pattern
Solution 2 (解决方案2 ):
Back
17
Class Adapter Pattern
类适配器模式
18
Class Adapter Pattern
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.
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
21
Class adapter pattern
22
示意性代码
23
24
public class {
private static ; // use the interface
as type
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
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
Adapter
Operation1: void (在方法中调用Operation1)
Operation2: void (在方法中调用Operation2)
Operation3: void (写全新的代码)
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
40
使用适配器模式进行设计的例子
设计类图的解释
• The first 4 methods are included in the off-shelf class
InfoValidator. But the last method
isValidSSNNum() is not included in InfoValidator.
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
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
使用类适配器模式进行的设计
使用适配器模式进行设计的例子
50
使用适配器模式进行设计的例子
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
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?
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:
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
网上二手车拍卖系统的设计
• 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
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 (施乐帕克研究中心)
19
MVC Design Patterns
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
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
28
MVC的优点
2) 容易独立地更新每个独立的软件模块
由于一个应用被分离为三个软件模块,因此,我
们可以独立地改变其中的一个模块,而不影响其
它两个模块。例如,一个应用的业务流程或者
业务规则的改变只需改动MVC的模型层。
• 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)
• 设计要点
• 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代码续
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
沈阳军区指挥部 抽象
部分
作战处 后勤处 实现
部分
师
陆战团 炮团 工兵团
将抽象部分与实现部分分开的军队机构设置
Design 1 (设计1,flat 设计)
Coffee
Coffee
MedSize SuperSize
MFragCoffee SFragCoffee
Extendibility (可扩展性不好)
Coffee
MedSize SuperSize
CoffeeSize
MedSize SuperSize
CoffeeKind
MilkCoffee FragrantCoffee
CoffeeKind
();
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;
}
}
应用桥模式设计的例子
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个英文字母按照顺序排列,按照如下方式两
两分成一组,本组内部 加密的时候互换:ab,
cd,…, wx, yz。
2.大写字母的加密方式也是如此,大写字母加密为
大写字母。
3.数字加密:01, 23,45, 67,
89
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
应用桥模式设计的例子
Back
思考题
• 是否可以将在抽象工厂模式中房屋信息系
统的例子改为由桥接模式设计
• 是个2维度问题
• Category: super, medium
• Kind: house, condo, semi detacher
Software 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
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软件体系结构的比较
Database
三层层次架构与MVC软件体系结构的比较
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
永久数据访问层
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
软件自动测试软件体系结构图
2. Case Studies
TestingGUI
<<interface>>
Testcase ResultVerification
+execute(int len); +isResultCorrect(int[] arr)
+getTimeTaken()
<<interface>>
SortAlgorithm
sort(int[] nums): int[]
应用层次架构设计的软件测试工具(功能测试):一个测试案例的情况
2. Case Studies
初始用户图形界面
2. Case Studies
在此用户图形界面上,可以选择待执行的测试案例,例
如,选择执行测试案例2得到以下的输出。
当选择了测试案例2并且执行测试的情况
2. Case Studies
2. Case Studies
(海王星)
(天王星)
2. Case Studies
Global Planning
Control
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
. 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
Receptionist 接待员
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?
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.
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.
Back
Another Example-account management
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.使用门面模式的设计
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
【例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
【例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
使用门面模式简单地产生一个门面类
几个例子的比较
几个例子的比较
• 例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
Back
(mainframe, -1970’s):
Prog 2
Prog 3
Prog 4
File
file
server
Client
File calls file
Client files
2. Evolution of client-server architecture
Database
SQL Server
Calls (DBMS)
SQL SQL
SQL
tier 1 tier 2
• 2-Tier is simple
• Small departmental decision support
• Simple Web publishing applications
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
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
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
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
Back
Professor:
Yushan (Michael) Sun
Fall 2016
Contents of this lecture
+main(String[ ] args )
Sorting
The advantages of this design
Sorting
Sorting
Dependency
inversion
Back
Something About Code for Sorting
Theory of the Strategy Pattern
Strategy
提供了一个
共同的接口
为调用准备环境
• 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:
av.find(a)
.
, clients interact with the context
exclusively.
Theory of the Strategy Pattern
goWork()
Context st.
+Context(Strategy st)
+goWork();
st.
Theory of the 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
-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
Context
-zodiac:ChineseZodiac zodiac
+Context(y:String,m:String, d: String)
+parseZodiac()
+setupZodiacToYear() <<interface>>
+createZodiacObj() ChineseZodiac
+getZodiacDescription()
+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()
<<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
:
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
P2P Client/Server
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
没找到
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
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.
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
服务层
JXTA
核心层
Return
Professor:
Yushan (Michael) Sun
Fall 2016
Contents of this lecture
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
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 }
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)
c.method()
关于状态的转换问题:
a) 是否所有的状态子类对象都需要由客户类创建,
然后再传递给Context类呢?
b) 还是客户类只创建一个“种子对象”,然后,
传递给Context类;再由Context类根据状态变
化的情况,负责创建所有的其它的对象呢?
回答:两种处理方法都可以,视具体情况而定
The State Design Pattern
持续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
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;
• 在状态类中,调用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:
withdraw
deposit
0 < balance <2000 -1000 < balance < 0
transaction fee ($2) transaction fee ($5)
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()
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
分布式的,多样的,动态的
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
.
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
.
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
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:
: 全球网格论坛与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
.
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
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 (税收问题)
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 (税收问题)
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.
• 该类可以使用一个聚合结构例如Java ArrayList
将被访问对象集合在一起,然后再使用一个循环
语句批量调用accept方法。
Back
27
28
假如我们要为一个电动自行车专卖商店写一个销售程
序。现在已经有一个层次类如下可供使用。
Battery BatteryBag BatteryCable BatteryChanger Controller
+getPrice +getPrice +getPrice +getPrice +getPrice
+getDescription +getDescription +getDescription +getDescription +getDescription
EBike
+getPrice
+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
WholeBike
+getPrice
+getDescription
设计要点:
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
EBike
+accept(v: Visitor)
+getPrice()
+getDescription()
WholeBike
+accept(v: Visitor)
+getPrice() 35
+getDescription()
获得某个配 获得某个配
件的价格 件的信息
36
Client
Battery
pv.visitBattery( );
+accept(Visitor v)
+getPrice:double
+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;
【例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)
利用访问者模式设计的计算机部件销售软件系统
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)
利用访问者模式设计的计算机部件销售软件系统 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
计算机部件销售的例子-代码
54
计算机部件销售的例子-代码
}
} 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
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
Zhang
Li Zhao
Introductory example to the mediator pattern
buildHouse() pasteWall()
:Wang :VillageHead
la :Huang
( ) yB
se
a ric
B ks
i ld ()
bu
:Li :Zhao
Introductory example to the 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
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()
m Colleague
Mediator
-m: Mediator
-c[ ]: Colleague +method()
+registerColleage(c: Colleague)
+operation()
Colleague1 Colleague2
ConcreteMediator -m: Mediator -m: Mediator
• 该设计类图由两部分组成,一部分是中介者类,
另外一部分是以上的参与者对象。
• 程序的构件说明:
• 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
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()
Back
Example of Mediator Pattern
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
Airport
BusinessMediator
Hotel TourCompany
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();
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;
bMediator.updateAllGuis(AIR, cusInfo);
}
}}
if (ae.getActionCommand().equals(SUBMIT)) {
setCusName();
String cusInfo = getCusName();
bMediator.updateAllGuis(AIR, cusInfo);
}
}}
}
catch (Exception ee){
ee. printStackTrace();
}
}
}
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
4)快速弹性Rapid elasticity.
•Capabilities can be rapidly and elastically
provisioned, in some cases automatically, to
Øquickly scale out(快速扩展), and
Ørapidly released (快速释放)
Øquickly scale in(快速收缩).
容易理解的“云”的定义
• 云是互联网服务,是复杂基础架构、应用、数据、
异构平台的抽象
• 云计算是云提供商提供的租借计算服务,可使外部
客户租借他们集群进行计算
– 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
提供并
提供并 且管理
且管理 的条目
提供并 的条目
且管理
的条目
云计算对各种出租服务的配置
Cloud Delivery Models
SaaS (软件即服务)
• SaaS is a software delivery model in which
software and associated data are centrally
hosted on the cloud.(软件与数据都在云端)
• 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.网络
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
网格计算 云计算
•异构资源 •同构资源
•不同机构 •单一机构
•虚拟组织 •虚拟机
•科学计算为主 •数据处理为主
•标准化 •尚无标准
•科学界 •商业社会
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
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
• 如何进行并行分布式计算(有一些算法)
• 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)
• 多租户是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
Load Balancer
每个租户都有为
其专门定制的应用程序版本。
例如财务系统定制版本:
1)清华大学财务系统
2)北京大学财务管理系统
3)哈工大财务系统
2022-11-3 49
Key Technologies of Cloud Computing
通过配置,可以
使得许多租户运
行同一个应用程
序的不同的实例。
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)
对于云计算
提供商来讲
费用太高
2022-11-3 53
Key Technologies of Cloud Computing
Ø 每个租户都有其
独立的数据模式;
Ø 容易实现和扩
展数据模型
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
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
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.
EAI EAI
EAI
EAI
EAI
• 互联网上运行的电子商务应用系统有很多个人用
户,例如电子商务平台淘宝,物流公司,网站,
如下图所示。
个人用户通过登
录网站,进行购 淘宝
买商品的交易。
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
interface
运输公司4
动态绑定并且 业务系统
自动进行交易
服务可以被发现,并且可以动态绑定
SOA Principle
Example:TV station uses services provided
by the Weather system
Find
Bind and
execute Contract
Register 包含很多服务提
供者目录
• SOA的5个实体
• SOA consists of the following 5 entities
configured together to support the find,
bind, and execute paradigm.
SOA Entities
Contract Contract
Service Service Service
Provider Registry Consumer
Contract Contract
SOA Entities
2. 获得格式 Contract
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.
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
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
大众用户
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 包含很多服务提
供者目录