Скачать презентацию Ingineria Programării Cursul 9 13 Aprilie 1 Скачать презентацию Ingineria Programării Cursul 9 13 Aprilie 1

e7ec8bf416b2c4c8d44952c5b7db261f.ppt

  • Количество слайдов: 63

Ingineria Programării Cursul 9 – 13 Aprilie 1 Ingineria Programării Cursul 9 – 13 Aprilie 1

Cuprins Din Cursurile trecute… ◦ Design Patterns Creational Patterns Structural Patterns Behavioral Patterns ◦ Cuprins Din Cursurile trecute… ◦ Design Patterns Creational Patterns Structural Patterns Behavioral Patterns ◦ ◦ ◦ Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor 2

Din Cursurile Trecute GOF: Creational Patterns, Structural Patterns, Behavioral Patterns Creational Patterns Structural Patterns Din Cursurile Trecute GOF: Creational Patterns, Structural Patterns, Behavioral Patterns Creational Patterns Structural Patterns 3

Behavioral Patterns 1 Behavioral patterns are concerned with algorithms and the assignment of responsibilities Behavioral Patterns 1 Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. These patterns characterize complex control flow that's difficult to follow at run-time. They shift your focus away from flow of control to let you concentrate just on the way objects are interconnected. 4

Behavioral Patterns 2 Encapsulating variation is a theme of many behavioral patterns. When an Behavioral Patterns 2 Encapsulating variation is a theme of many behavioral patterns. When an aspect of a program changes frequently, these patterns define an object that encapsulates that aspect. Then other parts of the program can collaborate with the object whenever they depend on that aspect. 5

Behavioral Patterns 3 These patterns describe aspects of a program that are likely to Behavioral Patterns 3 These patterns describe aspects of a program that are likely to change. Most patterns have two kinds of objects: ◦ the new object(s)that encapsulate the aspect, ◦ and the existing object(s) that use the new ones. Usually the functionality of new objects would be an integral part of the existing objects were it not for the pattern. 6

Chain of Responsibility Intent - Avoid coupling the sender of a request to its Chain of Responsibility Intent - Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Motivation - Consider a context-sensitive help facility for a graphical user interface. The user can obtain help information on any part of the interface just by clicking on it. The help that's provided depends on the part of the interface that's selected and its context; for example, a button widget in a dialog box might have different help information than a similar button in the main window. If no specific help information exists for that part of the interface, then the help system should display a more general help message about the immediate context—the dialog box as a whole, for example. 7

Chain of Responsibility 2 Hence it's natural to organize help information according to its Chain of Responsibility 2 Hence it's natural to organize help information according to its generality—from the most specific to the most general. 8

Chain of Responsibility 3 Structure 9 Chain of Responsibility 3 Structure 9

Chain of Responsibility 4 Applicability - Use this pattern when ◦ more than one Chain of Responsibility 4 Applicability - Use this pattern when ◦ more than one object may handle a request, and the handler isn't known a priori. ◦ you want to issue a request to one of several objects without specifying the receiver explicitly. ◦ the set of objects that can handle a request should be specified dynamically. 10

Chain of Responsibility - Example Suppose, we have a multi level filter and gravel Chain of Responsibility - Example Suppose, we have a multi level filter and gravel of different sizes and shapes. We need to filter this gravel of different sizes to approx size categories. We will put the gravel on the multi-level filtration unit, with the filter of maximum size at the top and then the sizes descending. The gravel with the maximum sizes will stay on the first one and rest will pass, again this cycle will repeat until, the finest of the gravel is filtered and is collected in the sill below the filters. Each of the filters will have the sizes of gravel which cannot pass through it. And hence, we will have approx similar sizes of gravels grouped. 11

Chain of Responsibility – Java 1 public class Matter { private int size; private Chain of Responsibility – Java 1 public class Matter { private int size; private int quantity; public int get. Size() { return size; } public void set. Size(int size) { this. size = size; } public int get. Quantity() { return quantity; } } public void set. Quantity(int quantity) { this. quantity = quantity; } 12

Chain of Responsibility – Java 2 public class Sill { public void collect(Matter gravel) Chain of Responsibility – Java 2 public class Sill { public void collect(Matter gravel) { } } public class Filter 1 extends Sill { private int size; public Filter 1(int size) { this. size = size; } public void collect(Matter gravel) { for(int i = 0; i < gravel. get. Quantity(); i++) { if(gravel. get. Size() < size) { super. collect(gravel); } else { //collect here. that means, only matter with less size will pass. . . } }}} 13

Command 1 Intent - Encapsulate a request as an object, thereby letting you parameterize Command 1 Intent - Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Also Known As - Action, Transaction Motivation - Sometimes it's necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request. For example, user interface toolkits include objects like buttons and menus that carry out a request in response to user input. But the toolkit can't implement the request explicitly in the button or menu, because only applications that use the toolkit know what should be done on which object. As toolkit designers we have no way of knowing the receiver of the request or the operations that will carry it out. 14

Command 2 The key to this pattern is an abstract Command class, which declares Command 2 The key to this pattern is an abstract Command class, which declares an interface for executing operations. 15

Command - Structure Open. Command prompts the user for a document name, creates a Command - Structure Open. Command prompts the user for a document name, creates a corresponding Document object, adds the document to the receiving application, and opens the document. 16

Command - Example A classic example of this pattern is a restaurant. A customer Command - Example A classic example of this pattern is a restaurant. A customer goes to restaurant and orders the food according to his/her choice. The waiter/ waitress takes the order (command, in this case) and hands it to the cook in the kitchen. The cook can make several types of food and so, he/she prepares the ordered item and hands it over to the waiter/waitress who in turn serves to the customer. 17

Command – Java 1 public class Order { private String command; public Order(String command) Command – Java 1 public class Order { private String command; public Order(String command) { this. command = command; }} public class Waiter { public Food take. Order(Customer cust, Order order) { Cook cook = new Cook(); Food food = cook. prepare. Order(order, this); return food; }} 18

Command – Java 2 public class Cook { public Food prepare. Order(Order order, Waiter Command – Java 2 public class Cook { public Food prepare. Order(Order order, Waiter waiter) { Food food = get. Cooked. Food(order); return food; } public Food get. Cooked. Food(Order order) { Food food = new Food(order); return food; } } 19

Interpreter 1 Intent - Given a language, define a representation for its grammar along Interpreter 1 Intent - Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Motivation - If a particular kind of problem occurs often enough, then it might be worthwhile to express instances of the problem as sentences in a simple language. Then you can build an interpreter that solves the problem by interpreting these sentences. For example, searching for strings that match a pattern is a common problem. Regular expressions are a standard language for specifying patterns of strings. Rather than building custom algorithms to match each pattern against strings, search algorithms could interpret a regular expression that specifies a set of strings to match. 20

Interpreter 2 Suppose the following grammar defines the regular expressions: ◦ expression : : Interpreter 2 Suppose the following grammar defines the regular expressions: ◦ expression : : = literal | alternation | sequence | repetition | '(' expression ')' ◦ alternation : : = expression '|' expression ◦ sequence : : = expression '&' expression ◦ repetition : : = expression '*' ◦ literal : : = 'a' | 'b' | 'c' |. . . { 'a' | 'b' | 'c' |. . . }* 21

Interpreter 3 Regular expressions 22 Interpreter 3 Regular expressions 22

Interpreter - Applicability Use the Interpreter pattern when there is a language to interpret, Interpreter - Applicability Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when ◦ the grammar is simple. ◦ efficiency is not a critical concern. 23

Interpreter - Example The “musical notes” is an “Interpreted Language”. The musicians read the Interpreter - Example The “musical notes” is an “Interpreted Language”. The musicians read the notes, interpret them according to “Sa, Re, Ga, Ma…” or “Do, Re, Me… ” etc and play the instruments, what we get in output is musical sound waves. Think of a program which can take the Sa, Re, Ga, Ma etc and produce the sounds for the frequencies. For Sa, the frequency is 256 Hz, similarly, for Re, it is 288 Hz and for Ga, it is 320 Hz etc… In this, case, we need these values set somewhere so, that when the system encounters any one of these messages, we can just send the related frequency to the instrument playing the frequency. We can have it at one of the two places, one is a constants file, “token=value” and the other one being in a properties file. The properties file can give us more flexibility to change it later if required. 24

Interpreter – Java 1 Musical. Notes. properties Sa=256 Re=288 Ga=320 public class Notes. Interpreter Interpreter – Java 1 Musical. Notes. properties Sa=256 Re=288 Ga=320 public class Notes. Interpreter { private Note note; public void get. Note. From. Keys(Note note) { Frequency freq = get. Frequency(note); send. Note(freq); } private Frequency get. Frequency(Note note) { // Get the frequency from properties file using Resource. Bundle // and return it. return freq; } } private void send. Note(Frequency freq) { Notes. Producer producer = new Notes. Producer(); producer. play. Sound(freq); } 25

Interpreter – Java 2 public class Notes. Producer { private Frequency freq; public Notes. Interpreter – Java 2 public class Notes. Producer { private Frequency freq; public Notes. Producer() { this. freq = freq; } } public void play. Sound(Frequency freq) { } 26

Iterator 1 Intent - Provide a way to access the elements of an aggregate Iterator 1 Intent - Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. Also Known As - Cursor Motivation - An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you want to accomplish. But you probably don't want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you will need. You might also need to have more than one traversal pending on the same list. 27

Iterator - Structure 28 Iterator - Structure 28

Iterator 3 - Applicability to access an aggregate object's contents without exposing its internal Iterator 3 - Applicability to access an aggregate object's contents without exposing its internal representation. to support multiple traversals of aggregate objects. to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration). 29

Iterator - Example For example, remote control of TV. Any remote control we use, Iterator - Example For example, remote control of TV. Any remote control we use, either at home/hotel or at a friend’s place, we just pick up the TV remote control and start pressing Up and Down or Forward and Back keys to iterate through the channels. 30

Iterator – Java 1 public interface Iterator { public Channel next. Channel(int current. Channel); Iterator – Java 1 public interface Iterator { public Channel next. Channel(int current. Channel); public Channel prev. Channel(int current. Channel); } public Channel. Surfer implements Iterator { public Channel next. Channel (int current. Channel) { Channel channel = new Channel(current. Channel+1); return channel; } public Channel prev. Channel (int current. Channel) { Channel channel = new Channel(current. Channel-1); return channel; } } 31

Iterator – Java 2 public class Remote. Control { private Channel. Surfer surfer; private Iterator – Java 2 public class Remote. Control { private Channel. Surfer surfer; private Settings settings; public Remote. Control() { surfer = new Channel. Surfer(); settings = new Settings(); } public get. Program(Channel. Surfer surfer) { return new Program(surfer. next. Channel()); } } 32

Mediator Intent - Define an object that encapsulates how a set of objects interact. Mediator Intent - Define an object that encapsulates how a set of objects interact. Motivation - Object-oriented design encourages the distribution of behavior among objects. Such distribution can result in an object structure with many connections between objects; in the worst case, every object ends up knowing about every other. 33

Mediator - Example A very common example can be airplanes interacting with the control Mediator - Example A very common example can be airplanes interacting with the control tower and not among themselves. The control tower knows exactly, where each of the airplanes is, and guides them whereas the airplanes have their own responsibilities of landing and takeoff. Another popular example is Stock exchange. In old days when there were no stock markets, the individual brokers used to buy or sell commodities among themselves. They used to face huge risks, of defaulting of counterparty, limited information (as, only limited deals in limited areas were possible), limited geographical reach, price variance (everyone could quote whatever price they wanted) and many more. 34

Memento Intent - Without violating encapsulation, capture and externalize an object's internal state so Memento Intent - Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. Also Known As - Token Motivation - Sometimes it's necessary to record the internal state of an object. This is required when implementing checkpoints and undo mechanisms that let users back out of tentative operations or recover from errors. You must save state information somewhere so that you can restore objects to their previous states. But objects normally encapsulate some or all of their state, making it inaccessible to other objects and impossible to save externally. Exposing this state would violate encapsulation, which can compromise the application's reliability and extensibility. 35

Observer 1 Intent - Define a one-to-many dependency between objects so that when one Observer 1 Intent - Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Also Known As - Dependents, Publish-Subscribe Motivation - A common side-effect of partitioning a system into a collection of cooperating classes is the need to maintain consistency between related objects. You don‘t want to achieve consistency by making the classes tightly coupled, because that reduces their reusability. 36

Observer 2 The Observer pattern describes how to establish these relationships between the key Observer 2 The Observer pattern describes how to establish these relationships between the key objects from this pattern: subject and observer. 37

Observer - Applicability When an abstraction has two aspects, one dependent on the other. Observer - Applicability When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. When a change to one object requires changing others, and you don't know how many objects need to be changed. When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled. 38

Observer - Structure 39 Observer - Structure 39

Observer - Example Below is an example that takes keyboard input and treats each Observer - Example Below is an example that takes keyboard input and treats each input line as an event. The example is built upon the library classes java. util. Observer and java. util. Observable. When a string is supplied from System. in, the method notify. Observers is then called, in order to notify all observers of the event's occurrence, in the form of an invocation of their 'update' methods - in our example, Response. Handler. update(. . . ). The Java Swing library makes extensive use of the observer pattern for event management 40

Observer – Java 1 public class Event. Source extends Observable implements Runnable { public Observer – Java 1 public class Event. Source extends Observable implements Runnable { public void run() { try { final Input. Stream. Reader isr = new Input. Stream. Reader( System. in ); final Buffered. Reader br = new Buffered. Reader( isr ); while( true ) { final String response = br. read. Line(); set. Changed(); notify. Observers( response ); } } catch (IOException e) { e. print. Stack. Trace(); } } } 41

Observer – Java 2 public class Response. Handler implements Observer { private String resp; Observer – Java 2 public class Response. Handler implements Observer { private String resp; public void update (Observable obj, Object arg) { if (arg instanceof String) { resp = (String) arg; System. out. println("n. Received Response: "+ resp ); } } } 42

Observer – Java 3 public class My. App { public static void main(String args[]) Observer – Java 3 public class My. App { public static void main(String args[]) { System. out. println("Enter Text >"); // create an event source - reads from stdin final Event. Source ev. Src = new Event. Source(); // create an observer final Response. Handler resp. Handler = new Response. Handler(); // subscribe the observer to the event source ev. Src. add. Observer( resp. Handler ); // starts the event thread Thread thread = new Thread(ev. Src); thread. start(); } } 43

State Intent - Allow an object to alter its behavior when its internal state State Intent - Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Also Known As - Objects for States Motivation - Consider a class TCPConnection that represents a network connection. A TCPConnection object can be in one of several different states: Established, Listening, Closed. When a TCPConnection object receives requests from other objects, it responds differently depending on its current state. For example, the effect of an Open request depends on whether the connection is in its Closed state or its Established state. The State pattern describes how TCPConnection can exhibit different behavior in each state. 44

State - Idea The key idea in this pattern is to introduce an abstract State - Idea The key idea in this pattern is to introduce an abstract class called TCPState to represent the states of the network connection. 45

State - Applicability Use the State pattern in either of the following cases: ◦ State - Applicability Use the State pattern in either of the following cases: ◦ An object's behavior depends on its state, and it must change its behavior at run-time depending on that state. ◦ Operations have large, multipart conditional statements that depend on the object's state. 46

Strategy Intent - Define a family of algorithms, encapsulate each one, and make the Strategy Intent - Define a family of algorithms, encapsulate each one, and make the minter changeable. Strategy lets the algorithm vary independently from clients that use it. Also Known As - Policy Motivation - Many algorithms exist for breaking a stream of text into lines. Hard-wiring all such algorithms into the classes that require them isn't desirable for several reasons: 47

Strategy - Structure With Strategy pattern, we can define classes that encapsulate different line Strategy - Structure With Strategy pattern, we can define classes that encapsulate different line breaking algorithms. 48

Strategy - Example In the strategy pattern algorithms can be selected at runtime. A Strategy - Example In the strategy pattern algorithms can be selected at runtime. A standard calculator that implements basic operations: +, -, * 49

Strategy – Java 1 interface Strategy { int execute(int a, int b); } class Strategy – Java 1 interface Strategy { int execute(int a, int b); } class Concrete. Strategy. Add implements Strategy { public int execute(int a, int b) { System. out. println("Called Concrete. Strategy. A's execute()"); return (a + b); }} class Concrete. Strategy. Sub implements Strategy { public int execute(int a, int b) { System. out. println("Called Concrete. Strategy. B's execute()"); return (a - b); }} class Concrete. Strategy. Mul implements Strategy { public int execute(int a, int b) { System. out. println("Called Concrete. Strategy. C's execute()"); return a * b; }} 50

Strategy – Java 2 class Context { Strategy strategy; public Context(Strategy strategy) { this. Strategy – Java 2 class Context { Strategy strategy; public Context(Strategy strategy) { this. strategy = strategy; } public int execute(int a, int b) { return this. strategy. execute(a, b); } } 51

Strategy – Java 3 class Strategy. Example { } public static void main(String[] args) Strategy – Java 3 class Strategy. Example { } public static void main(String[] args) { Context context; context = new Context(new Concrete. Strategy. Add()); int result. A = context. execute(3, 4); context = new Context(new Concrete. Strategy. Sub()); int result. B = context. execute(3, 4); context = new Context(new Concrete. Strategy. Mul()); int result. C = context. execute(3, 4); } 52

Template Method Intent - Define the skeleton of an algorithm in an operation, deferring Template Method Intent - Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Motivation - Consider an application framework that provides Application and Document classes. The Application class is responsible for opening existing documents stored in an external format, such as a file. A Document object represents the information in a document once it's read from the file. 53

Template Method - Example The template pattern is often referred to as the Hollywood Template Method - Example The template pattern is often referred to as the Hollywood Principle: "Don't call us, we'll call you. " Using this principle, the template method in a parent class controls the overall process by calling subclass methods as required. This is shown in several games in which players play against the others, but only one is playing at a given time. 54

Template Method – Java 1 abstract class Game { protected int players. Count; abstract Template Method – Java 1 abstract class Game { protected int players. Count; abstract void initialize. Game(); abstract void make. Play(int player); abstract boolean end. Of. Game(); abstract void print. Winner(); /* A template method : */ final void play. One. Game(int players. Count) { this. players. Count = players. Count; initialize. Game(); int j = 0; while (!end. Of. Game()) { make. Play(j); j = (j + 1) % players. Count; } print. Winner(); } } 55

Template Method – Java 2 class Monopoly extends Game { /* Implementation of necessary Template Method – Java 2 class Monopoly extends Game { /* Implementation of necessary concrete methods */ void initialize. Game() { //. . . } void make. Play(int player) { //. . . } boolean end. Of. Game() { //. . . } void print. Winner() { //. . . } /* Specific declarations for the Monopoly game. */ //. . . } class Chess extends Game { 56

Visitor Intent - Represent an operation to be performed on the elements of an Visitor Intent - Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. Motivation - Consider a compiler that represents programs as abstract syntax trees. It will need to perform operations on abstract syntax trees for "static semantic" analyses like checking that all variables are defined. It will also need to generate code. So it might define operations for type-checking, code optimization, flow analysis, checking for variables being assigned values before they're used, and so on. Moreover, we could use the abstract syntax trees for pretty-printing, program restructuring, code instrumentation, and computing various metrics of a program. 57

Visitor – Java 1 interface Car. Element. Visitor { void visit(Wheel wheel); void visit(Engine Visitor – Java 1 interface Car. Element. Visitor { void visit(Wheel wheel); void visit(Engine engine); void visit(Body body); void visit. Car(Car car); } interface Car. Element { void accept(Car. Element. Visitor visitor); } 58

Visitor – Java 2 class Wheel implements Car. Element { private String name; Wheel(String Visitor – Java 2 class Wheel implements Car. Element { private String name; Wheel(String name) { this. name = name; } String get. Name() { return this. name; } public void accept(Car. Element. Visitor visitor) { visitor. visit(this); } } class Engine implements Car. Element { …} 59

Visitor – Java 3 class Car { Car. Element[] elements; public Car. Element[] get. Visitor – Java 3 class Car { Car. Element[] elements; public Car. Element[] get. Elements() {return elements. clone(); } public Car() { this. elements = new Car. Element[] { new Wheel("front left"), new Wheel("front right"), new Wheel("back left") , new Wheel("back right"), new Body(), new Engine() }; } } class Car. Element. Print. Visitor implements Car. Element. Visitor { public void visit(Wheel wheel) { System. out. println("Visiting "+ wheel. get. Name() + " wheel"); } public void visit(Engine engine) {…} public void visit(Body body) {…} public void visit. Car(Car car) { System. out. println("n. Visiting car"); for(Car. Element element : car. get. Elements()) { element. accept(this); } System. out. println("Visited car"); } } 60

Visitor – Java 4 class Car. Element. Do. Visitor implements Car. Element. Visitor { Visitor – Java 4 class Car. Element. Do. Visitor implements Car. Element. Visitor { public void visit(Wheel wheel) { System. out. println("Kicking my "+ wheel. get. Name()); } public void visit(Engine engine) {… } public void visit(Body body) { … } public void visit. Car(Car car) { for(Car. Element car. Element : car. get. Elements()) { car. Element. accept(this); } } } public class Visitor. Demo { static public void main(String[] args){ Car car = new Car(); Car. Element. Visitor print. Visitor = new Car. Element. Print. Visitor(); Car. Element. Visitor do. Visitor = new Car. Element. Do. Visitor(); print. Visitor. visit. Car(car); do. Visitor. visit. Car(car); } } 61

Bibliografie Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides: Design Patterns: Elements of Bibliografie Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides: Design Patterns: Elements of Reusable Object-Oriented Software (Gang. Of. Four) 62

Links Gang-Of-Four: http: //c 2. com/cgi/wiki? Gang. Of. Four, http: //www. uml. org. cn/c%2 Links Gang-Of-Four: http: //c 2. com/cgi/wiki? Gang. Of. Four, http: //www. uml. org. cn/c%2 B%2 B/pdf/Design. Patterns. pdf Design Patterns Book: http: //c 2. com/cgi/wiki? Design. Patterns. Book About Design Patterns: http: //www. javacamp. org/design. Pattern/ Design Patterns – Java companion: http: //www. patterndepot. com/put/8/Java. Patterns. htm Java Design patterns: http: //www. allapplabs. com/java_design_patterns/java_desi gn_patterns. htm Overview of Design Patterns: http: //www. mindspring. com/~mgrand/pattern_synopses. h tm 63