Upload
calvin-hutchinson
View
236
Download
0
Embed Size (px)
Citation preview
Object-Oriented Design and Programming (Java)
2
Topics Covered Today
• 2.3 Advanced Class Design– 2.3.4 Design Patterns– 2.3.5 Singleton Pattern– 2.3.6 Strategy Pattern
3
Reference
• <<Design Patterns: Elements of Reusable Object-Oriented Software>> – ISBN 0-201-63361-2– <<设计模式:可复用面向对象软件的基础 >>机械工业出版社
• <<Head First Design Patterns >>– <<深入浅出设计模式 >> ISBN: 7-5641-0165-2
4
History
• Patterns originated as an architectural concept by Christopher Alexander.
• The Timeless Way of Building – 《建筑的永恒之道》
5
Alexander’s Pattern
6
Alexander’s Pattern.
7
Alexander’s Pattern..
• Patterns describe a solution so that it can be applied many times without ever being the same.
8
History
• In 1980s, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming.
9
History
• Design patterns gained popularity in computer science after the book
<<Design Patterns: Elements of Reusable Object-Oriented Software>>
by
Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Gang of Four or GoF) was published in 1994.
10
Design Pattern
• Design patterns describe practical solutions to common design problems that occur repeatedly in software development.
• A design pattern description consists of: – Pattern name
– A description of the problem that the pattern addresses
– A description of the solution (for instance: class structure)
– A discussion of the consequences of using the pattern
11
Classification
• Creational Patterns (创建模式 )– deal with object creation mechanisms
• Structural Patterns (结构模式 )– describe how classes and objects can be combined to form
larger structures.
• Behavioral Patterns (行为模式 )– identify common communication patterns between objects
and realize these patterns.
12
23 Design PatternsCreational Patterns (创建模式 )
Abstract Factory (抽象工厂 ) Prototype (原始模型 )Singleton (单例 ) Builder (构建器 )Factory Method (工厂方法 )
Structural Patterns (结构模式 )
Adapter (适配器 ) Bridge (桥梁 )Composite (合成 ) Decorator (装饰 )Façade (外观 ) Flyweight (享元 ) Proxy (代理 )
Behavioral Patterns(行为模式 )
Chain of Responsibility (责任链 ) Command (命令 )Iterator (迭代子 ) Mediator (调停者 )Memento (备忘录 ) Observer (观察者 )State (状态 ) Strategy (策略 ) Visitor (访问者 ) Template Method (模版方法 ) Interpreter (翻译器 )
13
Topics Covered Today
• 2.3 Advanced Class Design– 2.3.4 Design Patterns– 2.3.5 Singleton Pattern– 2.3.6 Strategy Pattern
14
One of a Kind
• In some applications, there are classes that should only be instantiated once.
• For instance:– system clock of an operating system; – one accounting system in a company;– object used for logging;– catalog of a library system– …
15
Answer These Questions?
• How could you create a single object?– New MyClass();
• What if wanted to create another MyClass object? Could it call new on MyClass again?– Yes, if it is a public class.
• And if not?– Well, if it is not a public class,only classes in the same
package can instantiate it. But they can still instantiate it more than once.
16
Answer These Questions?.
• Can we do this?
– Yes. I suppose it is a class that can not be instantiated because it has a private constructor.
• Is there ANY object that could use this private constructor?– The code in MyClass is the only code that can call it.
public class MyClass {
private MyClass() { }
}
17
Answer These Questions?..
• What does this mean?
– MyClass is a class with static method. – We can call the static method like this:
MyClass.getInstance();
• Why did you use MyClass instead of some object name?– Well, getInstance() is a static method, in other words, it is a
CLASS method. We need to use the class name to reference a static method.
public class MyClass {
public static MyClass getInstance() { }
}
18
Answer These Questions?…
• What if I put things together? Now can I instantiate a MyClass?– Yes
• Can you think of a second way to instantiate an object?– MyClass.getInstance();
public class MyClass {
private MyClass() { }
public static MyClass getInstance() {
return new MyClass();
}
}
19
Answer These Questions?….
• Can you finish the code so that only One instance of MyClass is ever created?
20
Solutionpublic class ASingletonClass {
private static ASingletonClass singletonInstance;
// other useful instance variable here
private ASingletonClass() { }
public static singleton getSingletonInstance() {
if(singletonInstance == null) {
singletonInstance = new ASingletonClass();
}
return singletonInstance;
}
// other useful methods here
}
21
Solutionpublic class ASingletonClass {
private static ASingletonClass singletonInstance;
// other useful instance variable here
private ASingletonClass() { }
public static ASingletonClass getSingletonInstance() {
if(singletonInstance == null) {
singletonInstance = new ASingletonClass();
}
return singletonInstance;
}
// other useful methods here
}
22
Solutionpublic class ASingletonClass {
private static ASingletonClass singletonInstance;
// other useful instance variable here
private ASingletonClass() { }
public static ASingletonClass getSingletonInstance() {
if(singletonInstance == null) {
singletonInstance = new ASingletonClass();
}
return singletonInstance;
}
// other useful methods here
}
23
Solutionpublic class ASingletonClass {
private static ASingletonClass singletonInstance;
// other useful instance variable here
private ASingletonClass() { }
public static ASingletonClass getSingletonInstance() {
if(singletonInstance == null) {
singletonInstance = new ASingletonClass();
}
return singletonInstance;
}
// other useful methods here
}
24
Solutionpublic class ASingletonClass{
private static ASingletonClass singletonInstance;
// other useful instance variable here
private ASingletonClass() { }
public static ASingletonClass getSingletonInstance() {
if(singletonInstance == null) {
singletonInstance = new ASingletonClass();
}
return singletonInstance;
}
// other useful methods here
}
Lazy instantiation(延迟实例化) is important for resource intensive objects.
25
Solutionpublic class ASingletonClass {
private static ASingletonClass singletonInstance;
// other useful instance variable here
private ASingletonClass() { }
public static ASingletonClass getSingletonInstance() {
if(singletonInstance == null) {
singletonInstance = new ASingletonClass();
}
return singletonInstance;
}
// other useful methods here
}
26
Singleton Pattern Defined
• The singleton pattern ensures that – only one instance of a class is created and – provides a method to access that one instance.
• Singleton pattern class diagram:
Singleton
-singletonInstance : Singleton
-Singleton()
+getSingletonInstance() : Singleton
27
Eagerly Created Singleton Instance
public class Singleton {
private static Singleton
singletonInstance = new Singleton();
private Singleton() { }
public static Singleton getSingletonInstance() {
return singletonInstance;
}
}
JVM create the unique instance of the Singleton when class is loaded.
28
Singleton Pattern Example
• Class ICarnegieInfo contains the contact information for iCarnegie. Only one instance of class ICarnegieInfo can be created.
ICarnegieInfo
-singletonInstance : ICarnegieInfo
-name: String
-address: String
-telephone: String
-ICarnegieInfo()
+getSingletonInstance() : ICarnegieInfo
+getName():String
+getAddress(): String
+getTelephone(): String
29
Code Study
• Unit 2.3.5 ICarnegieInfo.java
• Unit 2.3.5 ICarnegieInfoDemo.java
30
ICarnegieInfoDemo.javaimport java.io.*;
public class ICarnegieInfoDemo {
private static PrintWriter stdOut = new PrintWriter(System.out, true);
public static void main(String[] args) {
ICarnegieInfo companyInfo =
ICarnegieInfo.getSingletonInstance();
stdOut.println("Name: " + companyInfo.getName());
stdOut.println("Address: " + companyInfo.getAddress());
stdOut.println("Telephone: " + companyInfo.getTelephone());
}
}
31
Consequences
• The singleton pattern has the following benefits:
– A singleton class can control how and when client code accesses the single instance.
– A singleton class can be easily modified • if requirements change and the application needs to limit the
number of instances to a number other than one.
32
Topics Covered Today
• 2.3 Advanced Class Design– 2.3.4 Design Patterns– 2.3.5 Singleton Pattern– 2.3.6 Strategy Pattern
33
Started with a simple SimUDuck app
• Joe works for a company that makes a highly successful duck pond simulation game, SimUDuck. The game can show a large variety of duck species swimming and making quacking sounds. The initial designers of the system used standard OO techniques and created one Duck superclass from which all other duck types inherit.
34
Duck Class Diagram
quack()
swim()
display()
// other duck-like methods
Duck
display() {
// looks like a mallard }
MallardDuck
display() {
// looks like a redhead }
RedHeadDuck
The display() method is abstract, since all duck subclass looks different.
35
Need the Ducks to FLY
quack()
swim()
display()
fly()
// other duck-like methods
Duck
display() {
// looks like a mallard }
MallardDuck
display() {
// looks like a redhead }
RedHeadDuck
good or bad??
36
RubberDuckDuck
quack()
swim()
display()
fly()
RubberDuck
quack() {
// override to squeak
}
display()
RedHeadDuck
display()
MallardDuck
display()
37
DecoyDuck
DecoyDuck
quack() {
// override to do nothing
}
display()
fly() { // override to do nothing
}
1. Code is duplicated across subclass.
2. Runtime behavior changes are difficult.
RubberDuck
quack() { // override}
display()
fly() { // override to do nothing
}
38
Using Interface
Duck
swim()display()
Quackable
quack()
<<Interface>>Flyable
fly()
<<Interface>>
DecoyDuck
display()
RubberDuck
display()quack()
MallardDuck
display()fly()quack()
RedHeadDuck
display()fly()quack()
39
Design Principle
• Identify the aspects of your application that vary and separate them from what stays the same.
Duck Class
Flying behaviors
Quacking behaviors
pull out
what varies
40
Design Principle.
• Program to an interface, not an implementation.
fly()
<<interface>>
FlyBehavior
fly() {
// do nothing
}
FlyNoWay
fly() {
// implements duck flying
}
FlyWithWings
41
Program to interface
• Programming to an implementation would be:
– Dog d = new Dog(); d.bark();
• Programming to an interface/supertype would be:
– Animal a = new Dog(); a.makeSound();
• Assign concrete object at run time:
– Animal a = getAnimal(); a.makeSound();
makeSound()
<<interface>>
Animal
makeSound() { meow(); }
meow() {// meow sound}
Cat
makeSound() { bark();}
bark() { // bark sound}
Dog
42
Implementing the Duck Behavior
quack()
<<interface>>
QuackBehavior
quack() {
// rubber duck squesk
}
Squeak
quack() {
// implements duck quacking
}
Quack
quack() {
// do nothing
}
MuteQuack
43
Integrate the Duck Behavior
Duck
flyBehavior: FlyBehavior
quackBehavior: QuackBehavior
Duck()
swim()
display()
performQuack()
performFly()
public abstract class Duck {
QuackBehavior quackBehavior;
FlyBehavior flyBehavior;
public Duck() { }
public void performQuack() {
quackBehavior.quack(); }
public void performFly() {
flyBehavior.fly(); }
public void swim() {
System.out.println("All ducks float."); }
}
Each Duck has a reference to something that implements QuackBehavior interface
Rather than handling the quack behavior itself, the Duck object delegates that behavior to the object referenced by quackBehavior
44
Implementing the Duck SubclassDuck
flyBehavior: FlyBehavior
quackBehavior: QuackBehavior
Duck()
swim()
display()
performQuack()
performFly()
MallardDuck
MallardDuck()
display()
public class MallardDuck extends Duck {
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
public void display() {
System.out.println(" I am a real mallard duck ");
}
}
45
Define a set of Fly Behaviors//FlyBehavior.java
public interface FlyBehavior {
void fly();
}
// FlyWithWings.java
public class FlyWithWings implements FlyBehavior {
public void fly() { System.out.println("I am flying!"); }
}
// FlyNoWay.java
public class FlyNoWay implements FlyBehavior {
public void fly() { System.out.println("I can not fly."); }
}
46
Define a set of Quack Behaviors// QuackBehavior.java
public interface QuackBehavior {
void quack();
}
// Quack.java
public class Quack implements QuackBehavior {
public void quack() { System.out.println("Quack"); }
}
// MuteQuack.java
public class MuteQuack implements QuackBehavior {
public void quack() { System.out.println("<<silence>>"); }
}
// Squeak.java
public class Squeak implements QuackBehavior {
public void quack() { System.out.println("Squeak"); }
}
47
Test Class
// MiniDuckSimulator
public class MiniDuckSimulator {
public static void main (String[] args){
Duck mallard = new MallardDuck();
mallard.performQuack();
mallard.performFly();
}
}
Quack
I am flying!
48
Setting Behavior DynamicallyDuck
flyBehavior: FlyBehavior
quackBehavior: QuackBehavior
Duck()
swim()
display()
performQuack()
performFly()
setFlyBehavior()
setQuackBehavior()
public abstract class Duck {
QuackBehavior quackBehavior;
FlyBehavior flyBehavior;
public Duck() { }
public void performQuack() {
quackBehavior.quack(); }
public void performFly() {
flyBehavior.fly(); }
public void swim() {
System.out.println("All ducks float."); }
public void setFlyBehavior(FlyBehavior fb) {
flyBehavior = fb; }
public void setQuackBehavior(QuackBehavior qb) { quackBehavior = qb; }
}
49
ModelDuckDuck
flyBehavior: FlyBehavior
quackBehavior: QuackBehavior
Duck()
swim()
display()
performQuack()
performFly()
setFlyBehavior()
setQuackBehavior()
ModelDuck
MadolDuck()
display()
public class ModelDuck extends Duck {
public ModelDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new MuteQuack();
}
public void display() {
System.out.println("I am a model duck");
}
}
50
MiniDuckSimulator2//MiniDuckSimulator2
public class MiniDuckSimulator2 {
public static void main (String[] args) {
Duck mallard = new MallardDuck();
mallard.performQuack();
mallard.performFly();
Duck model = new ModelDuck();
model.performFly();
model.performQuack();
model.setFlyBehavior(new FlyWithWings());
model.setQuackBehavior(new Squeak());
model.performFly();
model.performQuack();
}
}
Quack
I am flying!
I can not fly.
<<silence>>
I am flying!
Squeak
51
SimUDuck app Class Diagram
Quack
quack()
Squeak
quack()
MuteQuack
quack()
FlyWithWings
fly()
FlyNoWay
fly()
MallardDuck
display()
RubberDuck
display()
DecoyDuck
display()
ModelDuck
display()
QuackBehavior
quack()
<<Interface>>Duck
swim()display()performQuack()performFly()setQuackBehavior()setFlyBehavior()
FlyBehavior
fly()
<<Interface>>
quackBehavior
flyBehavior
52
Another Example: TaxCalculator
53
Strategy Pattern
• "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it."
54
UML Class Diagram
55
Library Syatem
56
Requirement
• The library system could display the borrowers information with three formats:– Plain text
– HTML
– XML
57
Using Strategy Pattern
58
Exercise
• Program spec:– An action adventure game has many game characters,
such as king, queen, knight and troll. Each character can make use of one weapon to fight at a time, but can change weapons at any time during the game. These weapons include knife, bow and arrow, sword, axe.
• Use strategy pattern to design UML class diagram for this program.
59
Summary
• Singleton pattern ensures that – only one instance of a class is created and – provides a method to access that one instance.
• Strategy pattern– define a family of algorithms, encapsulate each one, and make
them interchangeable. – Strategy lets the algorithm vary independently from the
clients that use it.