ObjectOriented Design and Programming Java Topics Covered Today
Object-Oriented Design and Programming (Java)
Topics Covered Today • 2. 3 Advanced Class Design – 2. 3. 4 Design Patterns – 2. 3. 5 Singleton Pattern – 2. 3. 6 Strategy Pattern 2
Reference • <<Design Patterns: Elements of Reusable Object. Oriented Software>> – ISBN 0 -201 -63361 -2 – <<设计模式:可复用面向对象软件的基础>>机械 业出版社 • <<Head First Design Patterns >> – <<深入浅出设计模式>> ISBN: 7 -5641 -0165 -2 3
History • Patterns originated as an architectural concept by Christopher Alexander. • The Timeless Way of Building – 《建筑的永恒之道》 4
Alexander’s Pattern 5
Alexander’s Pattern. 6
Alexander’s Pattern. . • Patterns describe a solution so that it can be applied many times without ever being the same. 7
History • In 1980 s, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming. 8
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 Go. F) was published in 1994. 9
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 10
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. 11
23 Design Patterns Creational Patterns (� 建模式) Abstract Factory (抽象 厂) Singleton (� 例) Factory Method ( 厂方法) Prototype (原始模型) Builder (构建器) Structural Patterns (� 构模式) Adapter (适配器) Composite (合成) Façade (外� ) Proxy (代理) Bridge (� 梁) Decorator (装� ) Flyweight (享元) Behavioral Patterns (行� 模式) Chain of Responsibility (� 任� ) Command (命令) Iterator (迭代子) Mediator (� 停者) Memento (� 忘� ) Observer (� 察者) State (状� ) Strategy (策略) Visitor (�� 者) Template Method (模版方法 ) Interpreter (翻� 器) 12
Topics Covered Today • 2. 3 Advanced Class Design – 2. 3. 4 Design Patterns – 2. 3. 5 Singleton Pattern – 2. 3. 6 Strategy Pattern 13
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 –… 14
Answer These Questions? • How could you create a single object? – New My. Class(); • What if wanted to create another My. Class object? Could it call new on My. Class 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. 15
Answer These Questions? . • Can we do this? public class My. Class { private My. Class() { } } – 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 My. Class is the only code that can call it. 16
Answer These Questions? . . • What does this mean? public class My. Class { public static My. Class get. Instance() { } } – My. Class is a class with static method. – We can call the static method like this: My. Class. get. Instance(); • Why did you use My. Class instead of some object name? – Well, get. Instance() is a static method, in other words, it is a CLASS method. We need to use the class name to reference a static method. 17
Answer These Questions? … • What if I put things together? Now can I instantiate a My. Class? – Yes public class My. Class { private My. Class() { } public static My. Class get. Instance() { return new My. Class(); } } • Can you think of a second way to instantiate an object? – My. Class. get. Instance(); 18
Answer These Questions? …. • Can you finish the code so that only One instance of My. Class is ever created? 19
Solution public class ASingleton. Class { private static ASingleton. Class singleton. Instance; // other useful instance variable here private ASingleton. Class() { } public static singleton get. Singleton. Instance() { if(singleton. Instance == null) { singleton. Instance = new ASingleton. Class(); } return singleton. Instance; } // other useful methods here } 20
Solution public class ASingleton. Class { private static ASingleton. Class singleton. Instance; // other useful instance variable here private ASingleton. Class() { } public static ASingleton. Class get. Singleton. Instance() { if(singleton. Instance == null) { singleton. Instance = new ASingleton. Class(); } return singleton. Instance; } // other useful methods here } 21
Solution public class ASingleton. Class { private static ASingleton. Class singleton. Instance; // other useful instance variable here private ASingleton. Class() { } public static ASingleton. Class get. Singleton. Instance() { if(singleton. Instance == null) { singleton. Instance = new ASingleton. Class(); } return singleton. Instance; } // other useful methods here } 22
Solution public class ASingleton. Class { private static ASingleton. Class singleton. Instance; // other useful instance variable here private ASingleton. Class() { } public static ASingleton. Class get. Singleton. Instance() { if(singleton. Instance == null) { singleton. Instance = new ASingleton. Class(); } return singleton. Instance; } // other useful methods here } 23
Solution public class ASingleton. Class{ private static ASingleton. Class singleton. Instance; // other useful instance variable here private ASingleton. Class() { } public static ASingleton. Class get. Singleton. Instance() { if(singleton. Instance == null) { singleton. Instance = new ASingleton. Class(); } Lazy instantiation( 延迟实例化) is important for resource intensive objects. return singleton. Instance; } // other useful methods here } 24
Solution public class ASingleton. Class { private static ASingleton. Class singleton. Instance; // other useful instance variable here private ASingleton. Class() { } public static ASingleton. Class get. Singleton. Instance() { if(singleton. Instance == null) { singleton. Instance = new ASingleton. Class(); } return singleton. Instance; } // other useful methods here } 25
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 -singleton. Instance : Singleton -Singleton() +get. Singleton. Instance() : Singleton 26
Eagerly Created Singleton Instance public class Singleton { private static Singleton singleton. Instance = new Singleton(); JVM create the unique instance of private Singleton() { } the Singleton when class is loaded. public static Singleton get. Singleton. Instance() { return singleton. Instance; } } 27
Singleton Pattern Example • Class ICarnegie. Info contains the contact information for i. Carnegie. Only one instance of class ICarnegie. Info can be created. ICarnegie. Info -singleton. Instance : ICarnegie. Info -name: String -address: String -telephone: String -ICarnegie. Info() +get. Singleton. Instance() : ICarnegie. Info +get. Name(): String +get. Address(): String +get. Telephone(): String 28
Code Study • Unit 2. 3. 5 ICarnegie. Info. java • Unit 2. 3. 5 ICarnegie. Info. Demo. java 29
ICarnegie. Info. Demo. java import java. io. *; public class ICarnegie. Info. Demo { private static Print. Writer std. Out = new Print. Writer(System. out, true); public static void main(String[] args) { ICarnegie. Info company. Info = ICarnegie. Info. get. Singleton. Instance(); std. Out. println("Name: " + company. Info. get. Name()); std. Out. println("Address: " + company. Info. get. Address()); std. Out. println("Telephone: " + company. Info. get. Telephone()); } } 30
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. 31
Topics Covered Today • 2. 3 Advanced Class Design – 2. 3. 4 Design Patterns – 2. 3. 5 Singleton Pattern – 2. 3. 6 Strategy Pattern 32
Started with a simple Sim. UDuck app • Joe works for a company that makes a highly successful duck pond simulation game, Sim. UDuck. 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. 33
Duck Class Diagram Duck quack() swim() display() // other duck-like methods Mallard. Duck The display() method is abstract, since all duck subclass looks different. Red. Head. Duck display() { // looks like a mallard } display() { // looks like a redhead } 34
Need the Ducks to FLY Duck good or bad? ? quack() swim() display() fly() // other duck-like methods Mallard. Duck display() { // looks like a mallard } Red. Head. Duck 35 display() { // looks like a redhead }
Rubber. Duck quack() swim() display() fly() Mallard. Duck display() Red. Head. Duck display() 36 Rubber. Duck quack() { // override to squeak } display()
Decoy. Duck Rubber. Duck Decoy. Duck quack() { // override} display() fly() { // override to do nothing } quack() { // override to do nothing } display() fly() { // override to do nothing } 1. Code is duplicated across subclass. 2. Runtime behavior changes are difficult. 37
Using Interface <<Interface>> Flyable <<Interface>> Quackable Duck swim() display() fly() Red. Head. D uck display() fly() quack() Decoy. Duck Rubber. Duck display() quack() 38 quack() Mallard. Duck display() fly() quack()
Design Principle • Identify the aspects of your application that vary and separate them from what stays the same. Duck Class t pull ou ies ar what v Flying behaviors Quacking behaviors 39
Design Principle. • Program to an interface, not an implementation. <<interface>> Fly. Behavior fly() Fly. With. Wings fly() { // implements duck flying } Fly. No. Way fly() { // do nothing } 40
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. make. Sound(); • Assign concrete object at run time: – Animal a = get. Animal(); a. make. Sound(); <<interface>> Animal make. Sound() Dog Cat make. Sound() { bark(); } bark() { // bark sound} 41 make. Sound() { meow(); } meow() {// meow sound}
Implementing the Duck Behavior <<interface>> Quack. Behavior quack() Quack Mute. Quack Squeak quack() { // implements duck quacking } quack() { // rubber duck squesk } 42 quack() { // do nothing }
Integrate the Duck Behavior Each Duck has a reference to something that implements Quack. Behavior interface Duck fly. Behavior: Fly. Behavior quack. Behavior: Quack. Behavior public abstract class Duck { Quack. Behavior quack. Behavior; Duck() swim() display() perform. Quack() perform. Fly() Fly. Behavior fly. Behavior; public Duck() { } public void perform. Quack() { quack. Behavior. quack(); } public void perform. Fly() { Rather than handling the quack behavior itself, the Duck object delegates that behavior to the object referenced by quack. Behavior fly. Behavior. fly(); } public void swim() { System. out. println("All ducks float. "); } } 43
Implementing the Duck Subclass Duck fly. Behavior: Fly. Behavior quack. Behavior: Quack. Behavior Duck() swim() display() perform. Quack() perform. Fly() public class Mallard. Duck extends Duck { public Mallard. Duck() { quack. Behavior = new Quack(); fly. Behavior = new Fly. With. Wings(); } public void display() { System. out. println(" I am a real mallard duck "); Mallard. Duck } Mallard. Duck() display() } 44
Define a set of Fly Behaviors //Fly. Behavior. java public interface Fly. Behavior { void fly(); } // Fly. With. Wings. java public class Fly. With. Wings implements Fly. Behavior { public void fly() { System. out. println("I am flying!"); } } // Fly. No. Way. java public class Fly. No. Way implements Fly. Behavior { public void fly() { System. out. println("I can not fly. "); } } 45
Define a set of Quack Behaviors // Quack. Behavior. java public interface Quack. Behavior { void quack(); } // Quack. java public class Quack implements Quack. Behavior { public void quack() { System. out. println("Quack"); } } // Mute. Quack. java public class Mute. Quack implements Quack. Behavior { public void quack() { System. out. println("<<silence>>"); } } // Squeak. java public class Squeak implements Quack. Behavior { public void quack() { System. out. println("Squeak"); } } 46
Test Class // Mini. Duck. Simulator public class Mini. Duck. Simulator { public static void main (String[] args){ Duck mallard = new Mallard. Duck(); mallard. perform. Quack(); mallard. perform. Fly(); } } Quack I am flying! 47
Setting Behavior Dynamically Duck public abstract class Duck { fly. Behavior: Fly. Behavior quack. Behavior: Quack. Behavior quack. Behavior; Duck() swim() display() perform. Quack() perform. Fly() set. Fly. Behavior() set. Quack. Behavior() public Duck() { } Fly. Behavior fly. Behavior; public void perform. Quack() { quack. Behavior. quack(); } public void perform. Fly() { fly. Behavior. fly(); } public void swim() { System. out. println("All ducks float. "); } public void set. Fly. Behavior(Fly. Behavior fb) { fly. Behavior = fb; } public void set. Quack. Behavior(Quack. Behavior qb) { quack. Behavior = qb; } } 48
Model. Duck fly. Behavior: Fly. Behavior quack. Behavior: Quack. Behavior public class Model. Duck extends Duck { public Model. Duck() { Duck() swim() display() perform. Quack() perform. Fly() set. Fly. Behavior() set. Quack. Behavior() fly. Behavior = new Fly. No. Way(); quack. Behavior = new Mute. Quack(); } public void display() { System. out. println("I am a model duck"); Model. Duck } } Madol. Duck() display() 49
Mini. Duck. Simulator 2 //Mini. Duck. Simulator 2 public class Mini. Duck. Simulator 2 { public static void main (String[] args) { Duck mallard = new Mallard. Duck(); mallard. perform. Quack(); mallard. perform. Fly(); Quack I am flying! I can not fly. Duck model = new Model. Duck(); model. perform. Fly(); model. perform. Quack(); <<silence>> I am flying! Squeak model. set. Fly. Behavior(new Fly. With. Wings()); model. set. Quack. Behavior(new Squeak()); model. perform. Fly(); model. perform. Quack(); } } 50
Sim. UDuck app Class Diagram Duck quack. Behavior swim() display() perform. Quack() perform. Fly() set. Quack. Behavior() set. Fly. Behavior() <<Interface>> Quack. Behavior quack() Quack quack() fly. Behavior Decoy. Duck display() Model. Duck display() Rubber. Duck display() Squeak Mute. Quack quack() <<Interface>> Fly. Behavior fly() Fly. No. Way Mallard. Duck fly() display() 51 Fly. With. Wings fly()
Another Example: Tax. Calculator 52
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. " 53
UML Class Diagram 54
Library Syatem 55
Requirement • The library system could display the borrowers information with three formats: – Plain text – HTML – XML 56
Using Strategy Pattern 57
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. 58
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. 59
- Slides: 59