4/28 課程投影片一(program structuring, MVC) 檔案
Download
Report
Transcript 4/28 課程投影片一(program structuring, MVC) 檔案
NCCUCS 軟體工程概論
Program Structuring Principles
Prof. Chen, Kung
April 28, 2014
Agenda
• Program Design
– Be abstract!
– Programming to an Interface
• Program Structuring
– UI and API
– Model-View-Controller (MVC) pattern
• Web Programming Basics
– HTTP/HTML/CSS
– JavaScript
– Server-side code, Session and Cookies
Be Abstract!
• Abstraction
–Interfaces
–Encapsulated Implementation
• Using a well-defined interface to “protect”
the implementation
• Factoring out common structures
Parameterzing the operation details
• Design guideline:
Depend on Abstractions
Abstractions in Programming
• Two Basic forms of abstractions
– Parameterization
• Function parameters
– Sorting as an example: take comparison parameter
» Comparable/Comparator Interfaces in Java
• Type parameters
– Generics / parametric polymorphism
» List<Fruit>
– Abstract members
• Abstract classes
– The “template method” example shown in previous slides
• Interface
Sorting as an Example
• Consider the two signature for ‘sort’:
– void sort( aVector_int )
;只能sort vector of integers?
– void sort(aVector<T>, aComparator)
T x T -> Bool
• we need a comparison method to support sort,
but sorting should NOT depend on a particular
comparison method.
Writing a Comparator Class without Generics
• Compare two doggies by breed and then name
public class CmpDogByBreedAndName implements
Comparator {
public int compare(Object o1, Object o2) {
Dog d1 = (Dog) o1;
Dog d2 = (Dog) o2;
int retVal = d1.getBreed().compareTo(d2.getBreed());
if ( retVal != 0 ) return retVal;
return d1.getName().compareTo( d2.getName() );
}
}
•How to use with Collections.sort()
ArrayList dogList = …;
Collections.sort( dogList, new CmpDogByName() );
Collections.sort( dogList, new CmpDogByBreed() );
Appendix: Comparable vs. Comparator
Interfaces in Java
• java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has
the following meanings.
public class Employee implements
– positive – this object is greater than o1
– zero – this object equals to o1
– negative – this object is less than o1
Comparable {
private int empId;
private String name;
private int age;
// getters & setters
public class EmpSortByEmpId implements Comparator {
public int compareTo(Object o) {
public int compare(Object o1, Object o2) {
return this.empId –
return ((Employee)o1).getEmpId() –
((Employee)o).empId ;
((Employee) o2).getEmpId();
}
}
}
• java.lang.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the
following meanings.
– positive – o1 is greater than o2
– zero – o1 equals to o2
– negative – o1 is less than o1
http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html
}
Appendix: Generic Comparator in Java
import java.util.Arrays;
class Person implements Comparable<Person> {
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
}
public String toString() {
return firstName + " " + surname;
}
public int compareTo(Person person) {
int result = surname.compareTo(person.surname);
return result == 0 ? firstName.compareTo(((Person) person).firstName) :
result;
}
private String firstName;
private String surname;
}
http://www.java2s.com/Tutorial/Java/0200__Generics/UsingGenericComparableinterface.htm
Counter-Example of Being Abstract
Copy
Read
Keyboard
Write
Printer
Write
Disk
enum OutputDevice {printer, disk};
void Copy(OutputDevice dev){
int c;
while((c = ReadKeyboard())!= EOF)
if(dev == printer)
WritePrinter(c);
else
WriteDisk(c);
}
void Copy(){
int c;
while ((c = ReadKeyboard()) != EOF)
WritePrinter(c);
}
Too specific!
Not easy to change
or extend.
Will fix it later
Program to an Interface
Use
Interfaces/Abstract classes
often
The Copy Example Revisited
Use interfaces/Abstract classes
interface Reader { // or abstract class
public int read();
};
Copy
Reader
Keyboard
Reader
interface Writer {
public void write(int);
};
Writer
Printer
Writer
Disk
Writer
void copy(Reader r, Writer w){
int c;
while((c = r.read()) != EOF)
w.write(c);
}
Another Example of Being Abstract
An example: hardwired Engine object in a Car object
• How to make the Car run efficiently with a
TurboEngine?
• Only by changing the Car!
– ...in the given design
Depend on Abstraction
Class Car {
…
private abstractEngine eng;
void setEngine(AbstractEngine e) {
eng = e;
}
…
}
• A class must not depend on a concrete class!
• It must depend on an abstract class ...
• ...using polymorphic dependencies (calls)
Program Structure
(Software Architecture)
UI, GUI, API
Model-View-Controller (MVC)
大一程式設計: sequential
• Input-Process-Output model
• Flow of a typical sequential program
– Prompt the user
– Read input from the keyboard
– Parse the input (determine user action)
– Compute the result
– Generate output
– Repeat
Sequential Programming Example
Prompt the user
User input
Output results
NCCU/CS/WebProg
UI Code 與Computation Code混在一起
•UI可能要多變化,但應用程式的計算邏輯卻可以比較穩定
Application
•傳統寫法: 夾雜UI code
•不易抽換UI呈現方式
•或同時支援多個UI模式
•PC
•Smart Phones
•Tablets
•…
UI Code
Decouple UI Code
•UI可能要多變化,但應用程式的計算邏輯卻可以比較穩定
Application
UI Procedure
Main
Body
UI Procedure
現代應用程式的基本架構: UI
• Traditional approach: Input – Process – Ouput (IPO)
• 分為 (G)UI and Functional Part (FP)
AP
API
UI
FP
Advantages of this Approach
• Easily replace UI
• Easily enhance FP
• Facilitate Regression Tests
Regression
Tester Prog.
API
UI
FP
注意:單向或雙向
Graphical User Interface(GUI)
•進入視窗環境,多樣化的使用者介面
多種輸入元件:
•文字欄
•下拉選單
•按鈕選擇
•Checkbox勾選
•文字區域
•…
NCCU/CS/WebProg
GUI Event-Driven Programming
• Normal (control flow-based) programming
– Approach
• Start at main()
• Continue until end of program or exit()
• Event-driven programming
– Unable to predict time & occurrence of event
– Approach
• Start with main()in GUI library
• Build GUI
• Await events (& perform associated computation)
NCCU/CS/WebProg
GUI Example Program
NCCU/CS/WebProg
Simple I/O vs. GUI
• 傳統UI
– The Program drives the User
• >請輸入密碼
• ________
• > 輸入錯誤
• GUI
– The User drives the Program
– Event-driven
NCCU/CS/WebProg
Review:
Event-driven Programming in Java
•
•
•
•
•
Lecture 12
Event target (ex: button)
Event triggering (firing)
Event listeners (handers)
Event registration
Event handling (interception)
事件攔截示意圖
ActionAdapter
或 繼承
被按而觸發
UI 物件
(Button)
註
冊
Event
Handler
ActionListener
實
作
事件
(ActionEvent)
委任模式 (Delegation Model):事件不由物件本身處理,而委託另外的類別處理。
Lecture 12
Programming to an Interface and
CallBack
Decoupling 常用技巧
An Example: Timer Service
• Suppose you want to implements a Timer class in Java. You
want to be able to program your class to:
– start the timer
– have the timer measure some time interval
then carry out some action when the correct time has elapsed
Action: Alarm
• Use a callback function to link the timer and the client.
interface Timed { public void doAction(); }
29
class Timer extends Thread { //timer是一獨立執行緒
long interval;
Vector timedObjects;
Vector wakeUpTimes;
Timer(long t) { interval = t; }
public void register(Timed obj, long sleepTime) {//註冊
TimedObjects.addElement(obj);
wakeUpTimes.addElement(
new Long(sleepTime+System.getCurrentTimemills() ));
}
public void run() {//timer的 main body
while (true) {
Thread.sleep(interval);
for (int i=0; i<timeObjects.size(); i++) {
long t = System.getCurrentTimemills();
if (t >= ((Long)
wakeUpTime.elementAt(i) ).longValue()) {
( (Timed) timedObjects.elementAt(i)).doAction();
}
//callback
}
} }
The Observer Pattern
Design to an Interface
Behavioral Patterns - Observer
Intent
• Define a one-to-many dependency between objects so that
when one object changes state, all its dependents are notified
and updated automatically.
Observer
Observable
Subject
If changed
Observer
Observer
•Decouples a subject and its observers
•Inversion of dependency (from Pull to Push)
• Similar to Publisher and Subscriber pattern
Implementing the Observer Pattern
Step 1: Observers register with Observable
addObserver (this)
Observer1
addObserver (observer2)
Observer2
Model
Observable
Step 2. Observable notifies Observers
notifyObservers(Object arg)
Model
update(Observable o, Object arg)
Observer1
Observable (Model) may also send himself a notifyObservers() msg - no params
CallBack
Observer Pattern Support in java.util
Observable (abstract)
+addObserver()
+removeObserver()
+notifyObservers()
#setChanged()
#clearChanged()
+hasChanged()
…
Observer
interface
update()
if hasChanged() {
for all o in observers {
o.update()
}
clearChanged()
}
ConcreteObservable
setState()
…
setChanged();
notifyObservers();
ConcreteObserver
A Simple Example of Observer Pattern
public class Employee extends Observable {
float salary;
public setSalary(float newSalary){
salary=newSalary; // salary has changed
setChanged(); // mark that this object has changed, MANDATORY
notifyObservers(this, new Float(salary)); // notify all observers, MANDATORY
}
}
public class Manager implements Observer{
public void update(Observable obj, Object arg){
System.out.println("A change has happened and new salary is " + arg);
}
}
public class Demo(){
public static void main(String[] args){
Employee e = new Employee();
Manager m = new Manager();
e.addObserver(m); // register for observing
}
}
Appendix for Self-Study
Even-Driven Programming in
Java AWT
Event-driven Programming in Java
• During implementation
– Implement event listeners for each event
– Usually one event listener class per widget
• At run time
– Register listener object with widget object
– Java generates event object when events occur
– Java then passes event object to event listener
• Example of observer design pattern
Lecture 12
事件簡介
• Java 事件繼承樹
Semantic
Events
Low-Level
Events
Lecture 12
事件簡介
•
•
•
•
•
•
•
•
•
•
ActionEvent: 元件有動作 (Click, Change…) 時產生
AdjustmentEvent: 有捲動,縮放動作發生時產生
ItemEvent: 由 List / Checkbox / Choice 選擇時產生
TextEvent: TextField / TextArea 內部文字被改
ContainerEvent: 加入 / 移除元件時產生
FocusEvent: 取得 / 失去焦點時產生
PaintEvent: 元件被繪出 / 重繪時產生
WindowEvent: Window 縮小 / 放大 / 關閉…時產生
KeyEvent: Keyboard 被按時產生
MouseEvent: Mouse 被按時產生
Lecture 12
實作一個 Event Handler
• 步驟:
–
–
–
–
引入 java.awt.event.*
宣告一個 Class,準備作為 Event Handler
找出要攔截的 Event 名稱
找出該 Event 會被哪一種 Listener (監聽者,Java 以
Interface 實作之) 或 Adapter (接收者,Java 以 Class 實作
之)攔截到。
– 將 Event Handler Class 實作相對應的 Listener 或 Adapter
– 利用 addXXXXListener() 函數,將做好的 Event Handler
Class 打入物件中 (如:打入 Button, Frame, TextField…)
– 完成
Lecture 12
Listener 及其函數對照表
Lecture 12
Listener 及其函數對照表
Lecture 12
Event Handler 範例
import java.awt.*;
import java.awt.event.*;
public class LayoutTest implements WindowListener {
public static void main(String[] args) {
Frame frm = new Frame("Frame with Controls");
LayoutTest layTest = new LayoutTest();
frm.setLayout(new FlowLayout());
Label lbl = new Label("Here is a label.");
frm.add(lbl);
Button btn = new Button("Click Me");
frm.add(btn);
frm.addWindowListener(layTest);
frm.setBounds(100, 100, 250, 100);
frm.setVisible(true);
}
Lecture 12
Event Handler 範例
import java.awt.*;
import java.awt.event.*;
public class LayoutTest implements WindowListener {
public static void main(String[] args) {
Frame frm = new Frame("Frame with Controls");
LayoutTest layTest = new LayoutTest();
frm.setLayout(new FlowLayout());
Label lbl = new Label("Here is a label.");
frm.add(lbl);
Button btn = new Button("Click Me");
frm.add(btn);
frm.addWindowListener(layTest);
frm.setBounds(100, 100, 250, 100);
frm.setVisible(true);
}
Lecture 12
Event Handler 範例
public void windowActivated(WindowEvent e)
{}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e)
{}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e)
}
Lecture 12
{}
Adapter
• 說明
– 為了攔截一個事件,實作整個介面,太划不來。
– Java 提供了每個 Listener 的實作 Class,您只要繼承後,Override 您想要攔
截的事件即可
• 對照表
Listener
Lecture 12
Adapter
ComponentListener
ComponentAdapter
ContainerListener
ContainerAdapter
FocusListener
FocusAdapter
KeyListener
KeyAdapter
MouseListener
MouseAdapter
MouseMotionListener
MouseMotionAdapter
WindowListener
WindowAdapter
Adapter 範例
import java.awt.*;
import java.awt.event.*;
public class LayoutTest extends WindowAdapter {
public static void main(String[] args) {
Frame frm = new Frame("Frame with Controls");
LayoutTest layTest = new LayoutTest();
frm.setLayout(new FlowLayout());
Label lbl = new Label("Here is a label.");
frm.add(lbl);
Lecture 12
Adapter 範例
Button btn = new Button("Click Me");
frm.add(btn);
frm.addWindowListener(layTest);
frm.setBounds(100, 100, 250, 100);
frm.setVisible(true);
}
public void windowClosing(WindowEvent e)
System.exit(0);
}
}
Lecture 12
{
Model-View Controller (MVC)
An Architectural Pattern
架構程式的原則:分工,模組化
Separation of Concerns
Decouple UI Code
IO Code
Application
類似UI COmponent
Event-Driven
類似UI COmponent
Call-back
Motivating the MVC Pattern
How to simultaneously create multiple user interfaces (views) for same
object?
Views
Window
a
Window
b
Window
c
x 60 30 10
y 50 30 20
z 80 10 10
b
a
a
b
c
a = 50%
b = 30%
c = 20%
model
c
MVC 是原則,
實際運用上會有不同
Ref:
The simplest Model View Controller (MVC) Java example
Joseph Mack
http://www.austintek.com/mvc/
Model-View-Controller (MVC) Pattern
• Developed at Xerox PARC in 1978 (Smalltalk)
• Separates GUI into 3 components
– Model
– View
– Controller
application data & logic
visual interface
user interaction
View
Model
Controller
MVC Interaction Order
1.
2.
3.
4.
5.
6.
User performs action, controller is notified
Controller may request changes to model
Controller may tell view to update
Model may notify view if it has been modified
View may need to query model for current data
View updates display for user
6
4,5
Model
View
3
1
2
Controller
Java Swing (GUI Library)
• The Swing framework is rooted in MVC principles
– A Swing component is a view/controller pair
– A Swing component is associated with a model
– A Swing component is any JComponent subclass
Model
Component
update
change state
query
Model
UI object
View
Lecture 12
action
Controller
Delegate Model in Java Swing
Data
View
Output
Model
Controller
Input
Input
Output
Delegate =
Controller + View
Model
• The model used by Java’s swing merges the Controller and View into
a single entity called Delegate
Basics of Web Applications
Please refer to another set of slides
Use MVC to Structure Web
Applications
Controller
request
User
input
do
choose
view
View
Output
Render
Return
result
Data
Model
Access
data
Data
Access
MVC Pattern for Web Applications
Servlet
JB
EJB
JSP
專業分工, 各司其職 (Separation
Of Concerns)