csci3100 tutorial 9
TRANSCRIPT
-
8/2/2019 CSCI3100 Tutorial 9
1/26
Design Pattern
An introduction
-
8/2/2019 CSCI3100 Tutorial 9
2/26
Outline
What is design pattern Overview of design patterns
Singleton
Observer
-
8/2/2019 CSCI3100 Tutorial 9
3/26
What is design pattern
In OO software design, there are a lot of problemsthat occur repeatedly.
Design pattern is a general reusable solution to suchproblems
-
8/2/2019 CSCI3100 Tutorial 9
4/26
What is design pattern
Design pattern is not Finished design that can be translated into code directly
Design pattern is
A template that have a fixed structure
-
8/2/2019 CSCI3100 Tutorial 9
5/26
What is design pattern
Design pattern is good because It solves many practical problems
It is the best practice of software engineering
High cohesion
Low coupling Distillation of OO design
-
8/2/2019 CSCI3100 Tutorial 9
6/26
Overview of design patterns
Creational patterns Object creation mechanism
Behavioral patterns
Common communication pattern
Structural patterns Realize relationship between entities
-
8/2/2019 CSCI3100 Tutorial 9
7/26
Overview of design patterns
Creational Patterns
Abstract Factory Builder
Factory
Method Prototype Singleton
Structural Patterns
Adapter Bridge Composite Decorator Facade Flyweight Proxy
Behavioral Patterns
Chain of
Responsibility Command Interpreter Iterator
Mediator Memento Observer State
Strategy
Template
Method Visitor
-
8/2/2019 CSCI3100 Tutorial 9
8/26
Singleton
Suppose we want to Ensure only one instance of a certain class exists
Provide easy access to this instance
-
8/2/2019 CSCI3100 Tutorial 9
9/26
Singleton
The first approach Implement the class
Define a global variable instance of the class
Not quite working, because
This class can be instantiated somewhere else in theprogram
-
8/2/2019 CSCI3100 Tutorial 9
10/26
Singleton
Singletons approach Make the constructor private!
No instantiation will work
Provide a public static method getInstance
Easy access to the object
-
8/2/2019 CSCI3100 Tutorial 9
11/26
Singleton
Java version
// Singleton.java
public class Singleton {
private int count = 0;
private static Singleton singleton = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return singleton;
}
public void setCount(int c) {
count = c;
}
public int getCount() {
return count;}
}
-
8/2/2019 CSCI3100 Tutorial 9
12/26
Singleton
Java version
// Main.java
public class Main {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
s1.setCount(192);Singleton s2 = Singleton.getInstance();
System.out.println(s2.getCount());
Singleton s3 = Singleton.getInstance();
s3.setCount(206);
Singleton s4 = Singleton.getInstance();
System.out.println(s2.getCount());
System.out.println(s4.getCount());
}
}
Output:
192
206
206
-
8/2/2019 CSCI3100 Tutorial 9
13/26
Observer
A pattern used a lot in event-driven programming GUI programming
When user click confirm
Change program state (process data)
Change the interface (switch to next window interface)
Operation system
When a USB stick is plugged in
-
8/2/2019 CSCI3100 Tutorial 9
14/26
Observer
Observed object (called subject) maintains a list ofobservers
When event happens
All observers get notified about the event
Different observers may response differently to this event
-
8/2/2019 CSCI3100 Tutorial 9
15/26
Observer
Observed(abstract class)
Aobserved
(subclass)
Observer(Interface)
DigitObserver GraphObserver
-
8/2/2019 CSCI3100 Tutorial 9
16/26
Observer
Observed(abstract class)
Aobserved(subclass)
Observer(Interface)
DigitObserver GraphObserver
import java.util.*;
public abstract class Observed {
private Vector observers = new Vector();
public void attach(Observer o) {
observers.add(o);
}
public void detach(Observer o) {observers.remove(o);
}
public void Notify() {
for (Iterator it = observers.iterator(); it.hasNext(); ) {
Observer o = (Observer) it.next();
o.update(this);
}
}
public abstract int getState();
public abstract void setState(int n);
}
Vector to store observers
Notify each observer stored in vector
-
8/2/2019 CSCI3100 Tutorial 9
17/26
Observer
Observed(abstract class)
Aobserved(subclass)
Observer(Interface)
DigitObserver GraphObserver
public class AObserved extends Observed {
private int count = 0;
public int getState() {
return count;
}
public void setState(int n) {
count = n;Notify();
}
}
Call notify defined in super class
-
8/2/2019 CSCI3100 Tutorial 9
18/26
Observer
Observed(abstract class)
Aobserved(subclass)
Observer(Interface)
DigitObserver GraphObserver
public interface Observer {
public void update(Observed od);
}
public class DigitObserver implements Observer {
public void update(Observed od) {
int count = od.getState();
System.out.println("DigitObserver state => " + count);}
}
public class GraphObserver implements Observer {
public void update(Observed od) {
int count = od.getState();
System.out.print("GraphObserver state => ");
for (int i = 0; i < count; i++)
System.out.print("*");
System.out.println();
}
}
Implement update
Implement update
-
8/2/2019 CSCI3100 Tutorial 9
19/26
Observer
Observed(abstract class)
Aobserved(subclass)
Observer(Interface)
DigitObserver GraphObserver
// Main.java
public class Main {public static void main(String[] args) {
Observed od = new AObserved();
Observer digit = new DigitObserver();
Observer graph = new GraphObserver();
od.attach(digit);
od.attach(graph);
od.setState(8);
od.detach(digit);
od.setState(30);
}
}
-
8/2/2019 CSCI3100 Tutorial 9
20/26
Observer
Another example implemented in Python
class AbstractSubject:
def register(self, listener):
raise NotImplementedError("Must subclass me")
def unregister(self, listener):
raise NotImplementedError("Must subclass me")
def notify_listeners(self, event):
raise NotImplementedError("Must subclass me")
class Listener:
def __init__(self, name, subject):
self.name = name
subject.register(self)
def notify(self, event):
print self.name, "received event", event
class Subject(AbstractSubject):
def __init__(self):
self.listeners = []
self.data = None
def getUserAction(self):self.data = raw_input('Enter something to do:')
return self.data
# Implement abstract Class AbstractSubject
def register(self, listener):
self.listeners.append(listener)
def unregister(self, listener):
self.listeners.remove(listener)
def notify_listeners(self, event):
for listener in self.listeners:
listener.notify(event)
Sample code from wikipedia, refer to references
-
8/2/2019 CSCI3100 Tutorial 9
21/26
Observer
Another example implemented in Python
if __name__=="__main__":
# make a subject object to spy on
subject = Subject()
# register two listeners to monitor it.
listenerA = Listener("", subject)listenerB = Listener("", subject)
# simulated event
subject.notify_listeners ("")
# outputs:
# received event
# received event
action = subject.getUserAction()subject.notify_listeners(action)
#Enter something to do:hello
# outputs:
# received event hello
# received event hello Sample code from wikipedia, refer to references
-
8/2/2019 CSCI3100 Tutorial 9
22/26
Additional resources
Only two patterns are introduced in this tutorial Other patterns worth studying
MVC(Model Viewer Controller)
Adaptor
Factory method, etc.
-
8/2/2019 CSCI3100 Tutorial 9
23/26
Additional resources
Design pattern bible: Design patterns, elements of reusable object-oriented
software by E. Gamma, R. Helm, R. Johnson and J.Vlisside(Known as GoF)
Head first design patterns
Stevens Design pattern serials (Chinese)
Google and Wikipedia
http://home.so-net.net.tw/idealist/Patterns/http://home.so-net.net.tw/idealist/Patterns/ -
8/2/2019 CSCI3100 Tutorial 9
24/26
Summary
What is design pattern Singleton pattern
Observer pattern
-
8/2/2019 CSCI3100 Tutorial 9
25/26
Q&A
Any questions?
-
8/2/2019 CSCI3100 Tutorial 9
26/26
References
http://home.so-net.net.tw/idealist/Patterns/Singleton.html
http://sites.google.com/site/stevenattw/design-patterns/observer
http://zh.wikipedia.org/wiki/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F
http://home.so-net.net.tw/idealist/Patterns/Singleton.htmlhttp://home.so-net.net.tw/idealist/Patterns/Singleton.htmlhttp://sites.google.com/site/stevenattw/design-patterns/observerhttp://sites.google.com/site/stevenattw/design-patterns/observerhttp://zh.wikipedia.org/wiki/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8Fhttp://zh.wikipedia.org/wiki/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8Fhttp://zh.wikipedia.org/wiki/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8Fhttp://zh.wikipedia.org/wiki/%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8Fhttp://sites.google.com/site/stevenattw/design-patterns/observerhttp://sites.google.com/site/stevenattw/design-patterns/observerhttp://sites.google.com/site/stevenattw/design-patterns/observerhttp://home.so-net.net.tw/idealist/Patterns/Singleton.htmlhttp://home.so-net.net.tw/idealist/Patterns/Singleton.htmlhttp://home.so-net.net.tw/idealist/Patterns/Singleton.html