You are on page 1of 38

Chương

C ươ g 8
8: Mẫu
ẫu tthiết
ết kế
ế (patte
(pattern))

UML/NN 1
Phần mềm tốt?
Theo kiến trúc
„ Comodity (Tiện nghi)

„ Firmness ((Tính ổn định)


ị )
„ Delight (Tính mỹ quan)

UML/NN 2
Khó khăn của thiết kế phần mềm
„ Độ phức tạp
„ Tính bất qui tắc
„ Phần mềm có thể thayy đổi và luôn luôn thayy
đổi
„ Phần mềm không nhìn thấy được (invisible)

UML/NN 3
Nguyên lý thiết kế lớp
„ Nguyên lý đóng mở: mở với phát triển thêm
nhưng đóng với việc sửa code
„ Nguyên lý thay thế Liskov: Các lớp cơ sở có thể
thay thế bằng lớp con kế thừa
„ Nguyên lý nghịch đảo phụ thuộc: Phụ thuộc
vào trừu tương không phụ thuộc vào chi tiết (kiến
trúc phân tầng quá nhiều sẽ bất lợi)
„ Nguyên lý ISP (The Inteface Segregation
Principle): Nên tách giao diện (vd có chức năng
chung) dùng chung thành nhiều đặc thù

UML/NN 4
Mẫu thiết kế (Design Pattern)
„ Người thiết kế tốt có khả năng nhận ra những mẫu
giải quyết vấn đề và những mẫu tương ứng để giải
quyết vấn đề
„ Những đặc trưng (lớp,
(lớp nhiệm vụ,
vụ cộng tác),
tác) các
thuộc tính của thiết kế mà có thể điều chỉnh để cho
phép
p ép mẫu
ẫu thiết
t ết kế
ế giải
g ả quyết các vấn
ấ đề

5 CNPM/NN
Pattern…
„ Tên mẫu (Pattern name) - describes the essence of the
pattern in a short but expressive name
„ Mục đích (Intent) - describes the pattern and what it
does
„ Tên khác (Also-known-as) - lists any synonyms for the
pattern
„ Sự thúc đẩy (Motivation) - provides an example of the
problem
„ Khả năng g vận
ậ dụng
ụ g ((Applicability)
pp y) - notes specific
p
design situations in which the pattern is applicable

6 CNPM/NN
…Pattern
„ Cấu trúc (Structure) - describes the classes that are
required
q to implement
p the pattern
p
„ Lớp tham gia (Participants) - describes the
responsibilities of the classes that are required to implement
the pattern
„ Cộng tác (Collaborations) - describes how the
participants collaborate to carry out their responsibilities
„ Hệ quả ả (Consequences)
(C ) - describes
d ib theh “design
“d i forces”
f ”
that affect the pattern and the potential trade-offs that must
be considered when the pattern is implemented (đặt cho
b các
bạn á lựa
l chọn)
h )
„ Mẫu liên quan (Related patterns) - cross-references
g patterns
related design p

7 CNPM/NN
Các mẫu thiết kế
„ Creational Pattern (Mẫu kiến tạo):
„ Abstractional Factory Method Pattern
„ Builder pattern
„ Factory Method pattern
„ Prototype Pattern
„ Singleton Pattern…
„ S uc u e Pattern:
Structure a e (có mẫu
ẫu Co
Composite,
pos e,
Adaptor)
„ Behavioral Pattern: (có mẫu Observer)
8 CNPM/NN
Mẫu thiết kế Singleton
„ Cho phép có một thể hiện của lớp. Vd: Find
Di l
Dialog, Unikey,
U ik một
ột đối tượng
tượ ttoàn
à cục lư
lưu
giữ kết nối CSDL…

UML/NN 9
Singleton (kiến tạo)

Singleton

static uniqueInstance return uniqueinstance


i i
singletonData

static Instance()
SingletonOp()
GetSingletonData()

CS 406: 10
Design
Patterns
Singleton Code
Using system;
Class Singleston
{
private static Singleston instance;
Protect Singlestone() {}
public static SingleStone Instance()
{
if (instance==null)
instance = new SingleStone ();
return SingleStone;
}
}
UML/NN 11
ADAPTER (structure)
„ Tái sử dụng các lớp nhưng giao diện (interface)
khô tương
không tươ thí
thích
h
„ Có những vấn đề không tương thích tiềm tàng

4/16/2010 MF12
F21AS
Adapter
„ Có 2 mẫu:
„ Mẫu
ẫ cấu trúc Class
„ Mẫu Cấu trúc Object

4/16/2010 MF13
F21AS
Adapter1
Adaptee
Target
Client
request()
t() specificRequest()
ifi R t()

Adapter

request()

„ Đa thừa kế

4/16/2010 MF14
F21AS
Adapter2

<<interface>>
Client Target
request()

Adapter Adaptee

request() specificRequest()

4/16/2010 MF15
F21AS
Adapter example

class PayProcessor {
....
//this method expects a WeeklyEmployee object
public
bli static
t ti void
id printPay(WeeklyEmployee
i tP (W kl E l e)
)
{
System.out.println(e.getName()
+ “ is paid “ + e.getPay() ;
}
}

PayProcessor WeeklyEmployee

printPay(WeeklyEmp getName()
loyee e) getPay()
4/16/2010 MF16
F21AS
Example

PayProcessor
client
printPay(WeeklyEmp adaptee
loyee e)
?
WeeklyEmployee MonthlyEmployee
target
getName() getEmployeeName()
getPay() getMonthlySalary()

4/16/2010 MF17
F21AS
Biểu đồ lớp
Client - unaltered
Target
Pay -unaltered.
Processor WeeklyEmployee
printPay getPay()
(W kl
(Weekly getName()
Employee
e)
MonthlyAdapter MonthlyEmployee
MonthlyEmployee : me
getPay() getMonthlyPay()
getName() getEmployeeName()

Adaptor Adaptee
unaltered
Contains an adaptee object
Provides own implementation of
target’s methods – which call
MF18
4/16/2010 adaptee’s methods F21AS
MonthlyAdapter
public class MonthlyAdapter
extends WeeklyEmployee {

private MonthlyEmployee me; //composed with adaptee

//created
// t d with
ith adaptee
d t object
bj t
public MonthlyAdapter(MonthlyEmployee memp)
{ me = memp; }

//own implementation of target method,


//adapting to use adaptee’s instead
public String getName()
{ return me.getEmployeeName(); }
public int getPay()
{ return me
me.getMonthlySalary();
getMonthlySalary(); }
}

4/16/2010 MF19
F21AS
Test
class Test {
public static void main(String
p ( g arg[])
g[])
{
WeeklyEmployee we
= new WeeklyEmployee
y p y (
(“tim”,, 150);
);

PayProcessor.printPay(we);
MonthlyEmployee me =
new MonthlyEmployee(“jane”, 200);
MonthlyAdapter ma = new MonthlyAdapter (me);
PayProcessor printPay(ma);
PayProcessor.printPay(ma);
}
}

4/16/2010 MF20
F21AS
Mẫu thiết kế Observer (hành vi)
„ Bài toán thực tế: Một đối tượng thời gian để
đế giờ
đếm iờ được
đượ thể hiện
hiệ dưới nhiều
hiề hình
hì h thức
thứ
như đồng hồ số, đồng hồ kim… Ta có thể
„ Dễễ dàng thêm, bớt nhiều đối tượng thể ể hiện
„ Khi tay đổi đối tượng thời gian thì tất cả các thể
h ệ của
hiện ủ thời
hờ gian đều
đề thay
h đổ đổi theo
h

21 CNPM/NN
Observer
„ Intent: Phụ thuộc một nhiều khi một đối tượng biến
đổi trạng thái các đối tượng khác phụ thuộc sẽ được
biến đổi tự động
„ Motivation: Cần duy trì sự toàn vẹn giữa các đối
tượng có liên quan
„ Applicability:
„ Khi có 2 hướng một cái phụ thuộc vào một cái khác
„ Khi một
ộ biến đổi tới một
ộ đối tượng
ợ g đòi hỏi biến đổi những
g
đối tượng khác mà không biết bao nhiêu đối tượng cần
biến đổi
„ Khi một
ột đối tượng
tượ phảihải có
ó khả năng
ă thông
thô bá báo tới đối
tượng khác mà không cần biết rõ chúng
22 CNPM/NN
Mô hình Observer

Relative Percentages
A B C D
A
X 15 35 35 15 D
Y 10 40 30 20 B
C
Z 10 40 30 20
A B C D

A=10%
B=40%
C=30% Application data
Change notification
D 20%
D=20%
Requests, modifications
CS 406: 23
Design
Patterns
Observer-- Structure
Subject Observer
*

Attach(Observer) Update()
D t h(Ob
Detach(Observer)
)
Notify()

ConcreteSubject ConcreteObserver

subjectState observerState

GetState() Update()
SetState()

24 CNPM/NN
Observer– Sequence Diagram
aConcreteObserver: anotherConcreteObserver:
aConcreteSubject:
ConcreteObserver ConcreteObserver
ConcreteSubject

SetState()

Notify()
Update()

GetState()

Update()

GetState()

25 CNPM/NN
Observer-- Example
Subject Observer
*

Attach(Observer) Update()
D t h(Ob
Detach(Observer)
)
Notify()

ClockTimer
DigitalClock AnalogClock

ClockTimer *sub; ClockTimer *sub;


Update()
Update()
Draw() Draw()

26 CNPM/NN
Observer Example – Sample Code
class Subject;

class Observer {
public:
virtual ~Observer();
virtual void Update(Subject * theChngedSub) = 0;
protected:
t t d
Observer();
}

class Subject {
public:
virtual ~Subject();
virtual void Attach(Observer
( *);
);
virtual void Detach(Observer *);
virtual void Notify();
protected:
List <Observer*>
<Observer > *_observers;
observers;
};

27 CNPM/NN
…Observer Example…
void Subject :: Attach(Observer* o) {
_observers
observers-->Append(o);
>Append(o);
}

void Subject
j :: Detach(Observer*
( o)) {
_observers-->Remove(o);
}

void Subject :: Notify() {


ListIterator<Observer*> i (_observers);
for (i.First(); !i.IsDone(); i.Next()) {
iC
i.CurrentItem()->Update(this);
tIt () >U d t (thi )
}
}

28 CNPM/NN
…Observer Example…
class ClockTimer : public Subject {
public:
ClockTimer();

virtual int GetHour();


virtual int GetMinute();
virtual int GetSecond();
void Tick();
}

void ClockTimer :: Tick() {


// update internal time-keeping state
//…
Notify();
y();
}

29 CNPM/NN
…Observer Example…
class DigitalClock : public Widget, public Observer {
public:
DigitalClock(ClockTimer *);
);
virtual ~DigitalClock();

virtual void Update(Subject *);


virtual
i t l void
id Draw();
D ()
private:
ClockTimer* _subject;
}

DigitalClock :: DigitalClock(ClockTimer *s) {


_subject = s;
_
_subject->Attach(this);
j ( );
}
DigitalClock :: ~DigitalClock(ClockTimer *s) {
_subject->Detach(this);
}

30 CNPM/NN
…Observer Example
void DigitalClock :: Update(Subject *theChngedSub) {
if (theChngedSub == _subject){
Draw();
}
}
void DigitalClock :: Draw() {
// get the new values from the subject
int hour = _subject->GetHour();
int minute = _subject->GetMinute();
// …
//draw the digital clock
}

// main

ClockTimer *timer = new ClockTimer;


AnalogClock * analogClock = new AnalogClock(timer);
DigitalClock
g * digitalClock
g = new DigitalClcok(timer);
g ( );

31 CNPM/NN
Observer C# (tham khao file project)
using System;
using System.Collections;

public class Subject


{
private ArrayList _observer;

public Subject()
{
_observer = new ArrayList();
}
public void Attach(Observer o)
{
_observer.Add(o);
}

public void Detach(Observer o)


{
_observer.Add(o);
}
public void Notify()
{
for (int i = 0; i < _observer.Count; i++)
{
((
((Observer)_observer[i]).Update(this);
)_ [ ]) p ( );
}
}

}
UML/NN 32
Mẫu thiết kế Composite (kiến trúc)
„ Bài toán thực tế: Một máy có các chi tiết
máy,
á các
á chihi tiết máy
á có ó thể gồm
ồ các
á chi
hi tiết
máy đơn giản (chi tiết máy đơn) và có thể có
nhưng
hư chi hi tiết máy
á ((chi
hi tiết máy
á phức)
hứ ) mà à
gồm có những chi tiết máy đơn và các chi
tiết máy
á phức
hứ khác
khá
„ Giải quyết bài toán tính giá trị của các chi tiết:
giá
iá trị
t ị máy
á bằng
bằ giá iá trị
t ị của
ủ các
á chi
hi tiết máy
á đơn
đơ
và giá trị của chi tiết máy phức (bằng tất cả giá
trị của các chi tiết)

33 CNPM/NN
Composite
„ Intent (mục đích): Compose objects into tree structures to
represent
p part-whole
pa o hierarchies.
a Let clients treat
a individual
d dua
objects and compositions of objects uniformly
„ Motivation (sự thúc đẩy): components can be grouped to form
larger components
aPicture

aPicture aLIne aRectangle

aText aLine aRectangle

34 CNPM/NN
Ví dụ 1
Graphic *

Draw()
Add(Graphic)
Remove(Graphic)
GetChild(int)

Picture
Line Rectangle Text

Draw()
Draw() Add(Graphic)
Draw() Draw()
Remove(Graphic)
GetChild(int)

35 CNPM/NN
Ví dụ 2
Component *

Operation()
Add(Component)
Remove(Component)
GetChild(int)

Composite
Leaf

Operation()
Add(Component)
Operation() Remove(Component)
GetChild(int)

36 CNPM/NN
Cộng tác
„ Client tương tác với các đối tượng trong cấu
trúc kết hợp qua interface lớp kết hợp
„ Nếu đối tượng
ợ g nhận
ậ là lá thì xử lýý trực
ự tiếp
p
„ Nếu đối tượng nhận là một nốt kết hợp thì
chuyển yêu cầu tới thành phần con của nó

37 CNPM/NN
Ví dụ khác
Equipment *

Card FloppyDisk CompositeEquipment

Cabinet Chasis Bus

38 CNPM/NN

You might also like