design-patterns.pdf

Upload: alina-botezatu

Post on 06-Jul-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/18/2019 Design-Patterns.pdf

    1/80

  • 8/18/2019 Design-Patterns.pdf

    2/80

    Contents

    1. Concept o structural pattern . . . . . . . . . . . . . . . . . . . . . . . 42. Adapter pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    2.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    2.2. Causes o pattern occurrence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

    2.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.4. Results o pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    2.5. Example o a practical pattern application . . . . . . . . . . . . . . . .12

    3. Bridge pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15

    3.2. Causes o pattern occurrence . . . . . . . . . . . . . . . . . . . . . . . . . . .15

    3.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .163.4. Results o pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

    4. Composite pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20

    4.2. Causes o pattern occurrence . . . . . . . . . . . . . . . . . . . . . . . . . . .20

    4.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21

    4.4. Results o pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    4.5. Example o a practical pattern application . . . . . . . . . . . . . . . .23

    Lesson No. 2 

    Structuralpatterns

  • 8/18/2019 Design-Patterns.pdf

    3/80

  • 8/18/2019 Design-Patterns.pdf

    4/80

    STEP Computer Academy

    4

    1. Concept of structural

    patternBased on the definition o inormation systems, it is obvious

    that any sofware solution operates some block o data. Whenanalyzing them we obtain some inormation that allows us tomake business and regular decisions on management o the

    Inormation System itsel.Te analysis o data assumes that it should be arranged in a

    structure. On the one side, it allows to identiy different data(logically distinguish them), on the other side — to organizeelementary values into structured objects and their combinations.Data structuring is necessary to reflect the concepts used inthe analysis and display the relationships ormed between theobjects in the process o their occurrence.

    Object-oriented approach provides us with a wealth o toolsor description o structured concepts and reflection o theirrelationships. However, the organization o structure that connectsconcepts into a working system is critical or the effective useo inormation systems, as well as maintenance obtained in the

    result o the product development process.In general, design patterns reflect the best models o making

    decisions on engineering problems, which stand the test o timeand practice. Structural patterns provide models o organizationo data into structures, which solve the problem o organizationo data management in the most efficient way. It is understoodthat the data may be presented not only with atomic values, but

    also with all the objects existing within our application. 

  • 8/18/2019 Design-Patterns.pdf

    5/80

     Lesson 2

    5

    hen we will review basic structural patterns, which areconsidered to be the best practices o sofware developmentby the world community.

  • 8/18/2019 Design-Patterns.pdf

    6/80

    STEP Computer Academy

    6

    2. Adapter pattern

    2.1. Pattern purposeIn order to make the material easy-to-understand, as well

    as to simpliy the presentation, we will use the ollowingterminology that is specific with respect to the considered

    problem:Client is a class that uses (aggregates) an adaptee class.

    Adapter is a class that transorms the interace o adaptee classto the interace expected by the client.

    Purpose o the Adapter design pattern is to cast (adapt)the interace o adaptee to the interace that is expected bythe client.

    2.2. Causes of pattern occurrenceTe ollowing problem is widely met: there is some class

    in a set o tools that is to be used in order to solve a problem,not specific or the structure o class. For example, we have

    declared a data type called IPEndPoint that describes the concepto network appliance. It is authorized or such properties asIP-address, MAC-address and host name, which are used inorder to perorm an engineering analysis (or example, tracea package movement). Te analysis is perormed by a classthat aggregates a variety o objects o the IPEndPoint type.Tis class is called NetView. However, we tend to implement a

    graphical representation o the process and the result o analysis.

  • 8/18/2019 Design-Patterns.pdf

    7/80

     Lesson 2

    7

    In addition it should be displayed in the main window o ourapplication. Te problem is that the NetView class has not aninterace that is specific or the object o graphics system. Tatis why it cannot be used by window class in order to perormrendering. We cannot «rewrite» (change a source code and astructure, respectively) the NetView class in order to make itsuitable or the needs o application, because it is a part o theused types o dll-library provided by the third parties. Or we just do not want to «overload» the class structure, since it is

    critical or any tasks o our application.In this case, it is logical to use a mediator class. It will cast

    the NetView class to the desired data type using an inheritanceand define a rendering interace o the NetView type o data byoverriding the methods specific or the component o graphicssystem.

    Such a mediator class is commonly called an adapter.

     

  • 8/18/2019 Design-Patterns.pdf

    8/80

    STEP Computer Academy

    8

    2.3. Pattern structure

    Structure o the Adapter pattern is shown in the abovediagram.

    Involved elements: ■   Client  is a class that uses some auxiliary data types and

    expects them to have a standard interworking interace (interaceo application) described by the arget class.

     ■   Target  is a class containing an interace expected by the

    client.

  • 8/18/2019 Design-Patterns.pdf

    9/80

     Lesson 2

    9

     ■   Adaptee  is a class that is required or client operation,but its interace differs rom the one expected by the client.

     ■   Adapter  is a class casting the Adaptee class interace tothe arget class interace.

    In the above structure, an interace casting is carried outdue to the act that the Adapter class inherits both the Adapteeand arget classes, and thereore, it has both their interaces.Ten the Adapter class casts method calls, which are specificor the arget class interace, to the calls o the appropriate

    methods o the Adaptee class interace.Te below sequence diagram shows that calls o methods

    o the Adapter class object are reduced to the calls o methodso the object o its base class.

     

    Also it is possible to implement the Adapter pattern in analternative way. Its structure is shown in the below diagram.

  • 8/18/2019 Design-Patterns.pdf

    10/80

    STEP Computer Academy

    10

     

    In contrast to the previous structure, the Adaptee andAdapter classes are not related, but they are involved in anassociation relationship, i.e. the Adapter class aggregates theAdaptee class.

    Tus, the Adaptee class interace is casted to the arget classinterace due to the act that the method calls o the Adapterclass object, which are specific or the arget class interace,are casted to the appropriate methods o the Adaptee class

    object, encapsulated in the Adapter class. Te below sequencediagram demonstrates this process.

  • 8/18/2019 Design-Patterns.pdf

    11/80

     Lesson 2

    11

    2.4. Results of pattern useTe main positive result o use o the Adapter design pattern

    is a possibility to cast a class interace to the interace expectedby application in a quite flexible manner and without changingthe structure o class. It is necessary both in terms o eliminationo the redundancy o the types’ structure and modularity oapplications being created.

    Redundancy plays a negative part when we need to reusea written code (or example, in another application). Tiscode is called a reusable code. Te reusable code creation isconsidered to be a good practice, because it reduces the cost

    and increases the speed o the development. Also it increasesthe flexibility and scalability o applications being created dueto the modular structure o finished application.

    It is much easier to expand an application by adding newtypes than to completely recreate some o the modules.

     

  • 8/18/2019 Design-Patterns.pdf

    12/80

    STEP Computer Academy

    12

    2.5. Example of a practical patternapplication

    We will consider a specific example o use o the Adapterpattern that includes an application managing a company’sturnover. In order to control products, we will describe theProduct (product/item) data type that will be organized intoa collection o products by means o the ProductsCollectionclass.

    Also, our application controls other aspects o activity oa trading company. We will omit them in order to provide aproper transparency o the example.

    A data backup may be used to solve almost any task. In orderto implement a possibility o its creation, we decided that all thedata should be exported to separate xml-files. For this purposewe have implemented the XmlIO class reading and recordingan Xml-document. Its object is encapsulated with the windowclass o our application. In order to record a collection oproducts into a file, we have created the ProductXmlIOAdapterclass. It encapsulates a collection o products, implements thecasting o this collection to an xml-document, as well as thisxml-document to the collection.

    Tus, we implement the unction o recording the collectiono items into an xml- file. At the same time, we do not changethe structure o source data type, but eliminate a structureredundancy that might appear as a result o provisioningthe Product class with additional unctionality. Redundancyelimination is necessary, because the Product data type maybe used in order to cast the product inormation obtained

    rom the database to an object representation. Tis gives a

  • 8/18/2019 Design-Patterns.pdf

    13/80

     Lesson 2

    13

    possibility to perorm a urther analysis. While executingall these steps, the redundancy o type structure may createadditional difficulties. Also, such a modular structure addsflexibility, when maintaining a project, and makes it possibleto use (create) a reusable code.

    Te ollowing class diagram shows the above describedapplication.

  • 8/18/2019 Design-Patterns.pdf

    14/80

    STEP Computer Academy

    14

  • 8/18/2019 Design-Patterns.pdf

    15/80

     Lesson 2

    15

    3. Bridge pattern

    3.1. Pattern purposePurpose o the Bridge pattern is to separate an abstraction

    and its implementation in order to make them capable to varyindependently.

    3.2. Causes of pattern occurrenceUsually, i an abstraction (an abstract class) may have a ew

    specific implementations, they use inheritance in order todefine a number o classes o a similar or matching interace.Abstract class defines an interace or its descendants. Tisinterace is implemented by them in a variety o ways.

    However, this approach is not always flexible enough and hassome weak spots. Tey may lead to the code redundancy andcreate additional difficulties while maintaining a project. Allo that may significantly increase its price. Single inheritanceo abstraction interace, executed by a specific class, connectsimplementation and abstraction in a direct manner. his

    creates diiculties in the process o urther modiication(extension) o implementation and also does not allow us toreuse abstraction and its implementation separately rom eachother. Implementation seems to become firmly associatedwith abstraction.

    he Bridge design pattern places an interace and itsimplementation into dierent hierarchies. his allows us

    to separate an interace rom the implementation and use

  • 8/18/2019 Design-Patterns.pdf

    16/80

    STEP Computer Academy

    16

    them independently, as well as to combine any options oimplementation with various refined options o abstraction.

    3.3. Pattern structureTe Bridge design pattern is represented with the ollowing

    structural elements: ■ Abstraction defines an interace o abstraction and contains

    an implementor’s object defining an interace o implementation.

     ■ Implementor defines the interace or classes oimplementation. Implementor’s interace does not have toconorm to the abstraction interace. Interaces defined byabstraction and implementor may be quite different that isflexible. In general, implementor should identiy basic operations,which serve as a base or high-level logic o abstraction.

     ■ RefinedAbstraction extends an interace o certainabstraction.

     ■ ConcreteImplementor is a class that implements animplementor’s interace and defines its particular implementation.

    Abstraction and implementor orm a «bridge» together. Itconnects the refined abstraction and concrete implementation.Structure o the Bridge design pattern is presented below in

    the class diagram.

  • 8/18/2019 Design-Patterns.pdf

    17/80

     Lesson 2

    17

    3.4. Results of pattern useA main benefit provided by the Bridge design pattern is that

    abstraction is separated rom the implementation in terms o logicand structure providing a code with extra flexibility. Also, the Bridgepattern application improves such a qualitative characteristic othe code as extensibility, because abstraction and implementor

    pertain to different hierarchical structures. Tus, it becomespossible to extent an implementation regardless o abstraction,and vice versa.

    Another reason to use the Bridge design pattern is the actthat it allows us to hide implementation details rom the client,i.e. rom the application using an abstraction. It allows the clientnot to depend on a particular type o implementation in one

    case or another. 

  • 8/18/2019 Design-Patterns.pdf

    18/80

    STEP Computer Academy

    18

    Example o a practical pattern applicationWe are going to consider a specific example o the mixed graphics

    editor (editor that allows us to edit raster and vector graphics in acollaborative manner, i.e. within a single representation) in orderto understand the use o the Bridge design pattern.

    A model o application assumes an availability o some graphicalrepresentation operating by several abstract figures. Te interaceo interaction with such figures is described by the Figure interaceplaying a part o abstraction in this example.

    Te interace o implementor is determined by the FigureImpinterace, rom which VectorFigure and RasterFigure classes areinherited, respectively. VectorFigure and RasterFigure classesdescribe the implementation o rendering the vector and rasterfigures.

    Ater determination o implementation we can reine theabstraction describing an interace o a speciic igure (e.g.,ellipse). Afer that, you can associate a refined abstraction witha concrete implementation, or example, to define VectorEllipseand RasterEllipse classes, describing the vector and raster ellipses,respectively.

    Te model o application described above is shown below.

  • 8/18/2019 Design-Patterns.pdf

    19/80

  • 8/18/2019 Design-Patterns.pdf

    20/80

    STEP Computer Academy

    20

    4. Composite pattern

    4.1. Pattern purposeTe Composite pattern is designed to represent objects in

    the tree structure in the part-whole hierarchies.

    4.2. Causes of pattern occurrenceTe Composite pattern exists, because a «tree» structure isquite common and it is ofen used or the management o datao regular structure. Tis structure implements a part-wholehierarchy, assuming that an element o some data compositionmay be either an elementary member, or a similar composition.

    Te simplest implementation o such a structure with arecursive containment system may be expressed as the systemo types. It contains classes describing the basic componentsand classes, which will be used as containers or elementarycomponents.

    However, this approach has a serious disadvantage. A codeusing these classes must separately process the elements and

    their containers, even i in most cases they are processed in thesame way. Tis considerably complicates the implementationo application.

    Te Composite pattern offers a recursive structure thatallows us not to make decisions on the method o processingthe separate elements o the whole data collection.

    he key to understanding the nature o the Composite

    pattern is a definition o the abstract interace that is identical

  • 8/18/2019 Design-Patterns.pdf

    21/80

     Lesson 2

    21

    to elementary components and their containers. Since containerand elementary components are related and share a commonuser interace, container may be an element o another similarcontainer creating a comortable regular (recursive) structure.

    4.3. Pattern structure ■ Component describes an interace to objects and their

    compositions; implements the basic behavior that is specific

    or the individual elements and their compositions; defines aninterace to access the composition elements and to managethese elements; also it determines an interace to access a parentelement o the recursive structure.

     ■ Lea defines a single element o the composition anddescribes the behavior o primitive (basic) elements o theoverall structure.

     ■ Composition determines the behavior o componentscontaining child elements, encapsulates the child elements,implements the control operations and the access to childelements defined by a component interace.

     ■ Client manages the elements o composition by meanso the component interace.

    Te Composite pattern structure is presented below in theorm o a class diagram that is shown in the figure.

  • 8/18/2019 Design-Patterns.pdf

    22/80

    STEP Computer Academy

    22

  • 8/18/2019 Design-Patterns.pdf

    23/80

     Lesson 2

    23

    4.4. Results of pattern useTe Composite pattern application helps to simpliy the

    organization o elements in a containment structure o data andeliminates the code redundancy in the process o implementationo this task. Also, the Composite pattern makes the clientobject simpler and allows it to process basic components andtheir compositions in the same way in virtue o their unifiedinterace, determined by the class-component.

    Te Composite pattern simplifies the process o adding

    the new components. Regardless o whether new classes areelementary components or compositions, they will workwith a structure that had already existed at the time o theircreation. In other words, there is no need to change the clientwhile creating the new components.

    4.5. Example of a practical patternapplication

    We will consider the use o the Composite design patternon the basis o organization o a variety o elements o thegraphical user interace having a regular structure. In otherwords, any window may include not only controls, but also

    the other windows. Windows may be simplistically describedas the compositions o controls.

    In order to organize the Composite pattern or a certainproblem, we declare the UIElement abstract class. It describesthe element o graphical user interace and defines the interaceo basic behavior o the graphical interace element and thecontrol interace o child elements o the composition.

     

  • 8/18/2019 Design-Patterns.pdf

    24/80

    STEP Computer Academy

    24

    Basic behavior o the element o graphical user interaceincludes Hide, Paint and Show methods. Tey implement anability to display an element, redraw its graphical representationand hide it, respectively.

    Add, GetChild and Remove methods are defined in order tocontrol the access to child elements o the composition. Teyallow us to add a new child element, receive it and remove anelement rom the composition, respectively.

    Te Control class describes a control element that acts as a

    primitive element o Composite being implemented by us. Itimplements basic behavior. Te Window class is a compositiono controls. However, it also implements basic behavior, sinceit has a basic graphical representation.

    Te Application class plays a part o client associated witha certain window, i.e. it uses an object o the Window classand an interace described by the UIElement class.

    Model o the described application is shown in the classdiagram in the figure below.

  • 8/18/2019 Design-Patterns.pdf

    25/80

     Lesson 2

    25

  • 8/18/2019 Design-Patterns.pdf

    26/80

    STEP Computer Academy

    26

    5. Decorator pattern

    5.1. Pattern purposeTe Decorator pattern purpose is to implement a possibility

    to add a dynamic unctional to the object, as well as to allocateresponsibility or the implementation o separate unctionsbetween the individual classes.

    Te Decorator pattern is an alternative to the inheritancein terms o the unctional extension o objects.

    5.2. Causes of pattern occurrenceSubdivision o responsibility or the implementation o

    separate operations between the individual classes is a verypopular approach, since it creates a structure, each class owhich encapsulates the control logic with duties assigned toit. Both a modularity simpliying the development and anopportunity to close the access to operations or the class areo equal importance.

    Inheritance is one o the methods allowing the allocation

    o responsibilities or implementation o a common taskbetween different classes. However, this approach is inflexible,because in case o inheritance the added unction is staticallyassigned or all descendants o this class. In order to createdifferent types (with different unctionality), you must executeinheritance in all the possible combinations.

    Decorator allows us to combine the object unctionality

    according to its internal logic in a lexible manner and

  • 8/18/2019 Design-Patterns.pdf

    27/80

     Lesson 2

    27

    dynamically change the object unctionality at the runtime,since the addition o unction is reduced to the creation o acomponent object o a particular class.

    5.3. Pattern structureTe structure o the Decorator pattern is represented by

    the ollowing elements:■ Component is an abstraction o element that will be

    assigned with the «scenery» (composition). O course, the«scenery» shall be understood to mean not a visual design,but an addition o the specific unctions. Component containsa declaration o abstract operation. Later, decorator will addnew eatures in order to implement this particular operation.

     ■ ConcreteComponent is a component implementation. ■ Decorator is a class that inherits and aggregates a component.

    It overrides the operation implementation in order to perorma unction encapsulated in a component, and then adds a newunctionality.

  • 8/18/2019 Design-Patterns.pdf

    28/80

    STEP Computer Academy

    28

    Since Decorator is a special case o component (inheritsthe Component), then another Decorator may be used as anencapsulated component. It allows us to perorm a recursivesequence o the calls o redefined operation with gradualaccumulation o unctional (as shown above in the sequencediagram).

     

  • 8/18/2019 Design-Patterns.pdf

    29/80

     Lesson 2

    29

    ConcreteDecoratorA and ConcreteDecoratorB representprivate decorator implementations o the component.

    Structure o the Decorator design pattern is illustrated inthe class diagram below.

    5.4. Results of pattern use

    As mentioned above, the use o pattern allows us to implementthe allocation o responsibilities or the perormance o difficulttask among several classes in a more flexible manner thanwhen using the inheritance.

    On the other hand, the Decorator design pattern allows usto avoid redundancy o the class hierarchy, because it is notnecessary to create classes, which would include unctionality

    o the all necessary combinations. 

  • 8/18/2019 Design-Patterns.pdf

    30/80

    STEP Computer Academy

    30

    Example o practical pattern applicationWe will consider the example o model o the text editor

    with html-syntax highlighting.It is supposed to use the class o text view in order to

    implement the view logic o text inormation to a user. Temodel o text view organization is given below.

  • 8/18/2019 Design-Patterns.pdf

    31/80

     Lesson 2

    31

    On the one hand, the text view class (extView) is inheritedby the class o specific view implementation in the orm otext area (the extArea class) supporting the editing. In orderto maintain a possibility o extension o unctional o the text view, we have declared the extDecorator class. Actually, thisclass is implemented by the Decorator pattern. We create aconcrete implementation o the extDecorator class in orderto implement the possibility o html-syntax highlighting. Itencapsulates the logic o implementation o the html-syntax

    highlighting in the text view.When implementing the window rendering, where the text

     view is used (Paint is an event handler), it is created an imagehaving the size o the client area o application, or which thegraphics context is initialized. Object o the graphics context othe created image is transmitted to the Paint method o objecto the HtmlHighlightDecorator class. Te last calls the Paintmethod o object o the extArea class and, subsequently, theDrawColoredext method that is responsible or the highlightedtext rendering. Te sequence o calls is shown in the sequencediagram, given below.

  • 8/18/2019 Design-Patterns.pdf

    32/80

    STEP Computer Academy

    32

    Tus, afer returning the control to the Paint event handler owindow class, the highlighted text syntax will be rendered in animage created by the handler. Te last thing we do is renderingthe resulting image on the graphics context o window, to which

    the text view is related.

  • 8/18/2019 Design-Patterns.pdf

    33/80

     Lesson 2

    33

     

    Ten, such implementation will allow us to add and removea variety o decorating effects associated with the text editor ina quite flexible manner. For example, line numbers connectinglines or matched elements, as shown in the figure above.

    It is enough to declare several decorators and add them to thetext view in a window class, to which the text view is related.

    A generalized model is shown below.

  • 8/18/2019 Design-Patterns.pdf

    34/80

    STEP Computer Academy

    34

  • 8/18/2019 Design-Patterns.pdf

    35/80

     Lesson 2

    35

    6. Facade pattern

    Te Facade pattern is largely designed or encapsulation(hiding) o content and division o logical parts to independentsubsystems. In the real world the Facade pattern structureis applied in many situations. A good example is a ast-oodrestaurant, where you just come to the cashier’s desk and order

    the meals. As a rule, you are not interested in the detailedstructure o such a quick service restaurant. However, there isalso an office in this restaurant. You may come there and reerto it according to the narrow interace (or example, to becomea regular client). Tus, the restaurant gets two subsystems,which depend on each other in minimum. ogether they areadded up to one big system.

    «subsystem»

    Restaurant

    «subsystem»

    Office

    User

    PersonnelDepartment

    Reception desk Cashier’s desk 

    Kitchen

    Cleaning

    Warehouse

    Accountingdepartment

    Supportservices Marketing

  • 8/18/2019 Design-Patterns.pdf

    36/80

    STEP Computer Academy

    36

    6.1. Pattern purposePurpose o the Facade pattern is a definite structuring o

    classes into subsystems. You may access each o them througha single interace. When constructing application architecture,it is advisable to divide it into separate subsystems, whichshould be as independent as possible.

    Each part o program (a subsystem) will have its own Facadeclass, by means o which the management o this part oprogram will be perormed.

    6.2. Causes of pattern occurrenceIt is very difficult to design and build a large application

    at once. Architects have solved this problem by splitting theprograms into smaller subsystems. It allows us to build anypart o program without ocusing on other aspects o it andthen to continue with writing the next subsystem. I you buildindependent systems, it is possible to get a «sae» substitutabilityo its components or whole subsystems. I you get an independentsubsystem, you can use it in other projects again. Finally, ia team o programmers includes more than one person, it ispossible to commit a task to write a separate subsystem to each

    o them and then just connect them into a whole application.However, you had to reread a lot o documentation about

    this structure and understand how to use it in order to takeadvantage o an unamiliar subsystem. Te Facade pattern wascreated to solve this problem. It means that each subsystem willhave its own class. Tis class is a sort o the subsystem saver.It will be easy to interact with the structure through this class.

  • 8/18/2019 Design-Patterns.pdf

    37/80

  • 8/18/2019 Design-Patterns.pdf

    38/80

    STEP Computer Academy

    38

    6.3. Pattern structureTe Facade pattern assumes the existence o a subsystem

    in the program, or which the Facade class is created. Teexecution o operations rom the subsystem classes is triggeredby means o the Facade class.

    Also, it should be noted that the clients (subsystem users)should not have access to the subsystem classes.

    I it is possible, all o the subsystem objects should be keptin the Facade class. When calling a method rom the Facade

    object by the clients, it begins to work with the subsystemclasses.

  • 8/18/2019 Design-Patterns.pdf

    39/80

     Lesson 2

    39

    Te above example is not usual. Te Facade pattern mayincorporate more or less than three classes within a subsystem.Object o the Facade class is able to call the methods oelements o the subsystem, configure them, assign values totheir properties, and so on.

    Optionally, the Facade class must hold a subsystem classobjects in storage.

    It is possible to provide access to subsystem objects throughthe Proxy pattern. Sometimes, programmers do the Facade

    class static in order to make it possible to address this classrom any point o the program.

    6.4. Results of pattern useIt is easier to build the program starting with writing the

    separate independent subsystems, not the entire application atonce. In addition, we get a finished block o program that maybe used in other applications. It is also possible to replace oneo the subsystem components without disturbing the overallstructure o application.

    I we create a separate Facade class or every subsystem, itis easier to use such a system, as all the work o this structure

    is encapsulated (hidden) in the Facade class.It is possible to obtain greater perormance, flexibility and

    security o the application by using other patterns along withthe Facade pattern.

  • 8/18/2019 Design-Patterns.pdf

    40/80

    STEP Computer Academy

    40

    6.5. Case exampleLet’s consider the Facade pattern using the example o

    ollowing application: a simple translator o words. For instance,a user enters a word in Russian and gets a translation o thisword into English.

    Application should provide an opportunity to work with adictionary o pre-recorded words (save, load) rom a file. Also, thisapplication should be able to add new words into the text database.

  • 8/18/2019 Design-Patterns.pdf

    41/80

     Lesson 2

    41

    Te program is provided with a subsystem designed towork with a dictionary. Access to it will be obtained throughthe Facade class object.

    Diagram o classes o the application is displayed above.A user will manage the system through the Facade class(FacadeFileBase) that, in turn, calls objects o the subsystem.

  • 8/18/2019 Design-Patterns.pdf

    42/80

    STEP Computer Academy

    42

    7. Flyweight pattern

    7.1. Pattern purposehe purpose o pattern is a storage-eicient use o the

    computer’s memory. Tis is achieved by means o a properway o operation with a large number o small objects.

    In order to understand the pattern concept, it is necessary

    to learn how to separate internal and external eatures othe object. Internal object eature is a property that is storedwithin the object. In other words, it is an instance o class thatincludes a property (a variable) created inside it and storedas long as the object is «living». External eature is a propertythat is transerred to the object as an argument to one method(or a ew methods). It exists as long as the method is beingperormed.

    Te essence o pattern is to transorm the internal eaturesinto the external ones. Afer that it is not necessary to createmany objects, but only one that will be «displayed» in differentways depending on what external properties are applied thereto..

    7.2. Causes of pattern occurrenceAter «migration» to the object-oriented programming it

    becomes easier to program, because all objects seem to be «real».O course, it is associated with a number o difficulties. Whencreating a model o application, there is an urge to place objectsaccording to the principles o object-oriented programming. For

    example, a chair consists o a seat and legs, and a seat includes

  • 8/18/2019 Design-Patterns.pdf

    43/80

     Lesson 2

    43

    more additional parts. I we describe such architecture in detail,it may arise a situation, when there will be created too manyobjects. Application having such a structure will suffer rom«lags». What shall we do, when the required level o «details» isunreachable or a computer?

    Answer: It is necessary to separate logical and physical conceptiono the application. In programming we can ound such situations,when one and the same entity is placed in two (or more) locations.For example, logically we have a chair, consisting o a seat and

    legs. Physically, in the program it was created an object o a legthat appears in different locations. In order to make an objectappearing in different places, it is enough to transmit a numbero parameters to an object when calling the «display» methodrom it. Tese parameters will indicate where and how to displaythis element. Applying this approach when constructing thearchitecture, a programmer will obtain an application that willuse computer resources in an efficient way.

    7.3. Pattern structureAn object occurring in several locations at the same time is

    called an opportunist. Tese objects are provided with access

    by means o actory. Te client creates objects o opportunistsusing the actory. It calls a method returning the opportunistobject and receiving an object identifier that is to be returned.

    Factory holds objects o opportunists (a collection, anarray or individual objects) in storage. It is important that theobjects should be created at the client’s first request. As it wasmentioned above, when receiving the subsequent requests,

    they should get a created object stored inside the actory. 

  • 8/18/2019 Design-Patterns.pdf

    44/80

    STEP Computer Academy

    44

    When calling the GetObj method, a user passes an objectID to this method. Object ID is needed i an object with suchan index has been already created. It must be returned as aresult o the method operation. However, i the object was notcreated, it would be necessary to create it and record into theactory storage. Afer that, it should be returned as a result omethod operation.

    Further, the GetObj method is presented or review.Classes A, B, C are inherited rom the base class describing

    an interace o interaction with all the types o opportunists.

  • 8/18/2019 Design-Patterns.pdf

    45/80

  • 8/18/2019 Design-Patterns.pdf

    46/80

    STEP Computer Academy

    46

    Further, the GetObj method is presented or review.

    public IFlyweightInterface GetObj(int Index)

    {  // Take an object from the collection by index.  IFlyweightInterface D = CollectionObj[Index] as IFlyweightInterface;

      // Check, if object does not exist.  if (D == null)  {  // Creation of objects.  switch (Index)  {  case 0:  D = new A();

      break;  case 1:  D = new B();  break;  case 2:  D = new C();  break;  }  // After the creation of objects, add them to the collection  CollectionObj.Add(D, Index);  }

      // Return the object resulting from the collection or a newly created one.  return D;}

    Classes A, B, C are inherited rom the base class describingan interace o interaction with all the types o opportunists.

    7.4. Results of pattern useI you apply this pattern to your application, you get significant

    memory savings. Te result will remain the same even i wewill take into account that when gaining access to the object,the actory method time is lost (GetObj in this case). However,the efficiency o storage will be obtained only i the objects

    will contain a minimum number o internal properties when

  • 8/18/2019 Design-Patterns.pdf

    47/80

     Lesson 2

    47

    the external ones will be transerred in response to the calls.External properties should be defined using the algorithms.Te basic idea o pattern is to use memory in an efficient wayby means o the computational perormance.

    Access to the objects o opportunists should be obtainedthrough the actory methods only, since it will add flexibilityand a possibility to customize an object within the actorymethods.

    You should apply the pattern, when there are a lot o objects

    in your application and it is possible to describe their conditionby means o the external eatures, and the external eaturesmay be described and assigned by calculation.

  • 8/18/2019 Design-Patterns.pdf

    48/80

    STEP Computer Academy

    48

    7.5. Case exampleLet’s consider a console application that will display and

    calculate the result o battle between two armies.

  • 8/18/2019 Design-Patterns.pdf

    49/80

     Lesson 2

    49

    Human, Motor and ank classes differ rom each other bythe values o the internal properties and the method displayinga fighting unit to the screen.

    he FactoryUnit class object will hold in storage romzero to three objects in the orm o Unit within the ListUnitscollection that was specially created or this purpose. Classeso clients will be able to get access to the object by calling themethod rom the actory and passing the list object to it. Tisobject will indicate a particular Unit that should be returned

    as the result o method call.Te Player class will use actory in order to obtain and display

    the objects’ properties. However, all o the objects o playerswill actually use 3 instances o classes o Unit descendantsonly, and this should provide a storage-efficiency.

    Program is a major class containing the Main methodand the Battle method. Program management is perormedwithin the Main method. Te Battle method is responsible orcalculations showing the result o battle between two armieso two players.

  • 8/18/2019 Design-Patterns.pdf

    50/80

    STEP Computer Academy

    50

    8.1. Pattern purposeTe purpose o pattern is the creation o system providing

    an access to the object through a special substitute object.

    Tis allows us to achieve greater flexibility in the operation

    with a target class object.

    8. Proxy pattern

    Te Proxy pattern is ofen called a substitute pattern. Further,the main class that will be discussed is reerred to us as asubstitute or a proxy. Both terms are correct and describe thesame class/object.

    Proxy is an object providing a transit access to another object.

    Substitute is an object that externally looks in the same wayas the main one, but it has no internal unctionality.

    A substitute or a proxy object externally looks in the sameway as the object represented by it. However, all o its internalunctionality is a kind o a tunnel providing the client classeswith a possibility to access the main objects.

    Additionally, a substitute or a proxy object may be calleda stand-in object.

    Client Substitute arget class

  • 8/18/2019 Design-Patterns.pdf

    51/80

     Lesson 2

    51

    I the target class object will occupy a lot o space afer itscreation and there is no guarantee that the object will be neededin the application, it is possible to create a target object whenthe client calls the method o the substitute object at the firsttime. It will speed the application perormance up i the objectwill not be used. However, i the object is created, then it willnot be so «harmul» or the program perormance.

    Such a system o access will allow us to use a target class inthe same, but more protected way (it is possible to perorm

     various checks o the accepted parameters within a substitute).For example, i a target class is a calculator, it just adds twoparameters into the method arguments and perorms basicmathematical computations. Within the substitute o thecalculator class, it is possible to check that the calculator willnot be given such a task, as to «divide by zero».

    You can use structure o the proxy pattern in order to createan «object» sent into another name space. For example, targetclass is described in the name space that or some reason isimpossible (or uncomortable) to connect. In this case we areable to create a substitute that will be located in the «needed»name space and the target class object will be created withinthe substitute taken rom another name space.

    8.2. Causes of pattern useSyntax and structure o the code o some programmers should

    be clear or other programmers. I you build an applicationusing a proxy pattern in order to access the objects, check thedata within the substitute objects and execute logical operations

    within the target class, then it is quite easy to explain another

  • 8/18/2019 Design-Patterns.pdf

    52/80

    STEP Computer Academy

    52

    programmer, where checks and basic logical operations areexecuted. In general, it is airly easy to explain the structure oapplication by means o the patterns.

    Perhaps, you have already seen the applications, which continuetheir running afer starting and only afer 5 seconds or morethey begin to display an interace. It happens, because whenyou start running the application, it begins to download all oits modules immediately, creates all instances o the needed (orneedless) classes or the application operation. You can create

    a substitute o a large object when launching an application inorder to partially solve this problem. Substitute is only a modelthat is not as large as the target object, and thereore it is createdin a aster manner. A large object will be created only i it isnecessary. A necessity appears when the client classes will workwith an object substitute that will orward all the requests tothe newly created target object.

    8.3. Pattern structureTe Proxy pattern assumes the presence o object (hereinafer

    reerred as a «target class») that will be accessed via a speciallycreated object substitute.

  • 8/18/2019 Design-Patterns.pdf

    53/80

     Lesson 2

    53

    However, a substitute object should not externally differrom the target object class, because both classes must beinherited rom a single interace.

    In the below example, the Math target object is created alongwith the substitute object, because the Math class is not largeand it will be created in a quicker way.

    Te example shows how to use a substitute object in orderto perorm various checks beore the immediate transer odata to the target class.

    8.4. Results of pattern use

    When providing the access to the pattern through thesubstitute object, we obtain an additional level o work withthe target object. At this level, we can deal with optimizationcreating target objects as long as they will be used. You canperorm a data validation beore transerring it to the targetobject. You can also enter the logging o access to an objectwithin the substitute object (or example, calculate how many

    times the summability method has been called in the calculator).

  • 8/18/2019 Design-Patterns.pdf

    54/80

    STEP Computer Academy

    54

    8.5. Case exampleLet’s consider the structure o «inormational shop» application

    in order to better understand this pattern. Te Shop class isavailable within the application architecture. It is accessedthrough the ProxyShop class. Te Shop class has a methodthat accepts a line containing the key and then returns a line

    with inormation, i possible. 

  • 8/18/2019 Design-Patterns.pdf

    55/80

     Lesson 2

    55

    he ProxyShop class protects the Shop class rom thepossibility o its «brutorsing». Also, the Shop object is createdwhen it is required in the program only. In other words, it iscreated when someone tries to get inormation using the key.

    Te class diagram o this application is displayed below.

  • 8/18/2019 Design-Patterns.pdf

    56/80

    STEP Computer Academy

    56

    public string GetInfo(string Key){  if (Brut < 3)  {  if (s == null)  {  s = new Shop();  }

      string Ret = s.GetInfo(Key);

      if (Ret == "null")  {  Brut++;  return "Incorrect code, error number:" + Brut;  }  Brut = 0;  return Ret;  }  return "You have no access";

    }

    Te GetIno method o Shop just returns the key value.

    public string GetInfo(string Key){  String Resoult = Information[Key] as string;  if (Resoult == null)

      {  return "null";  }  else  {  return Resoult;  }}

    Te GetIno method o ShopProxy perorms the objectcreation and access control.

  • 8/18/2019 Design-Patterns.pdf

    57/80

     Lesson 2

    57

    9. Analysis and comparison

    of structural patternsYou have already studied all o the structural patterns: ■ Adapter is a pattern that allows us to «adapt» an object to

    a different interace in order to gain access to it. For example,there is an Operation1 method within the object. We needto make it to be called OperationA. Purpose o the Adapter

    pattern is to «edit» an access interace to the target object. ■ Bridge is a pattern that allows us to separate the abstraction

    and implementation, when there is an objects’ hierarchy describedin an abstract manner. In addition, a specific system hierarchywill be implemented later. Purpose o the Bridge pattern isto build independent abstraction and implementation, andprovide the client with abstraction, by means o which it willbe able to manage the implementation.

     ■ Composite is a structural pattern that builds tree objects.Te purpose o this pattern is to build a tree-like structure inorder to store the objects.

     ■ Decorator is a pattern that allows us to compose structurein such a way that a ew objects are displayed as one. Te

    number o internal objects may vary at a high rate. ■ Facade is a structural pattern that explains how to build

    large applications o small independent subsystems. Te patternpurpose is to create a narrow and intuitive interace in orderto work with the subsystem.

     ■ Flyweight is a pattern that allows us to use the memoryin an efficient manner i the program has a lot o small objects

    and their status may be transerred into the external properties,

  • 8/18/2019 Design-Patterns.pdf

    58/80

    STEP Computer Academy

    58

    which are calculated by means o the algorithms. ■ Proxy involves the creation o substitute object or the target

    object. For this reason, it is able to provide greater flexibility,storage-efficiency and protection.

    We should select patterns considering their purpose, becauseat first glance it may seem that the patterns are similar. It seemsthat some o them have a similar structure. However, everypattern has a purpose. For example, you might think the Facadeand Proxy patterns are very similar, but they are applied or

    different purposes. Te purpose o the Facade pattern is tocreate a narrow interace or the subsystem operation. Te Proxypattern protects the target object.

    Structures o the Composite and Decorator patterns are also very similar, but you should start with the purpose o theirapplication. Te Composite pattern structures the objects andthe Decorator pattern allows us to create separate types ounctionality and connect them into one object.

    Ofen people do not see the difference between the Facadepattern and the Adapter pattern, because it seems that theyhave the same purpose. Tis purpose is to change or modiythe interace o access to one or a ew objects. However, usingthe adapter we are able to work with an old interace o access

    to the object and use a new one. In turn, the Facade patterncreates a new more ocused interace.

    It is important to note the act that pattern is not a standardo the program structure. In practice, we might hear: «Herewe have an architecture that is similar to the Flyweight patternarchitecture. However, different types o objects are returnedrom different methods within the actory».

  • 8/18/2019 Design-Patterns.pdf

    59/80

     Lesson 2

    59

    10. Examples of practical

    application of structuralpatternsTe first example is an application that uses the Adapter

    and Decorator structural patterns. An application will be a texteditor including a possibility to open a text file. However, it will

    not use the controls designed or editing and provided by thestandard system o .NE Framework types (such as extBoxand RichextBox). Actually, the purpose o the example is toshow an approach used or organization o the control elementexecuting the text editing.

    he Adapter pattern will be used to connect the classperorming the text control (control reers to the receipt, storageand editing) with some graphical context that is the extAreaclass. Te extView class will perorm the text rendering.

     

  • 8/18/2019 Design-Patterns.pdf

    60/80

    STEP Computer Academy

    60

    A model o connection o the text area with the graphicscontext using the Adapter pattern is shown in the above diagram.

    Te GraphicsView interace defining a standard elementinterace with a graphical view is declared.

    he extView class inherits the GraphicsView and theextArea.

     

  • 8/18/2019 Design-Patterns.pdf

    61/80

     Lesson 2

    61

    Further, we will use the Decorator pattern in order to designthe control element. In particular, we will determine twodecorators: the first one will perorm rendering o the ramearound the text area. Te second one will add a scroll bar tothe text area and execute the text view rendering with dueregard to the displacement o the scroll bar.

    A general model is shown below.

  • 8/18/2019 Design-Patterns.pdf

    62/80

    STEP Computer Academy

    62

    Ater declaration o classes in accordance with theabovementioned model, we will get a structure o classesthat is shown in the class diagram below.

  • 8/18/2019 Design-Patterns.pdf

    63/80

     Lesson 2

    63

    We should note that the model does not always consistentwith the implementation. Tereore an UML-diagram and aclass diagram o the finished project may significantly differrom each other. However, general approach remains unchanged.In order to add a class diagram to a project, we should call acontext menu o the project in the SolutionExplorer windowand select the creation o class diagrams.

    It is necessary to fill the orm in the ollowing way: addmenu, bar and the Dock eature that should be set to Fill.

    You should get a result that is similar to the represented one.

    Further, we will consider the application code by classesshown in the class diagram.

    Below we can see a graphics interace element or an elementthat may be rendered in the graphics context.

    Menu

    Bar

  • 8/18/2019 Design-Patterns.pdf

    64/80

    STEP Computer Academy

    64

      public interface GraphicsView  {  Panel Parent { get; set; }  int Offset { get; set; }

      void Paint(System.Drawing.Graphics e, Rectangle updateRectangle);  }

    Te GraphicViewDecorator interace inherits a graphicsarea. It differs by the act that it defines the View property othe GraphicsView type only, because the Decorator shouldhave a link to the view that is to be decorated.

      public interface GraphicsViewDecorator : GraphicsView  {  GraphicsView View { get; set; }  }

    Te text area is described below. It includes methods oprocessing the text that is to be added into the __text field. Tisprocess is carried out by means o the KeyPressed window eventhandler. Te KeyDown event handler serves or processingthe movement o internal pointer o the text area by pressingthe Lef and Right buttons.

      public class TextArea  {

      public delegate void TextChangedHandler(object sender, EventArgs e);  public event TextChangedHandler TextChanged =

    new TextChangedHandler(TextArea_TextChanged);  string __text = "";  public int Pointer { get; set; }  public string Text 

    {  get  {  return __text;  }

  • 8/18/2019 Design-Patterns.pdf

    65/80

     Lesson 2

    65

      set  {  __text = value;  TextChanged(this, new EventArgs());

      }  }  static void TextArea_TextChanged(object sender, EventArgs e)  {  }  public virtual void KeyPressEventHeandler(object sender, KeyPressEventArgs arg)  {  if ((int)arg.KeyChar == 8)  {  if (Text.Length > 0)  {

      Text = Text.Remove(Pointer-1, 1);  Pointer--;  }  }  else if (!Char.IsControl(arg.KeyChar))  {  Text = Text.Insert(Pointer++, arg.KeyChar.ToString());  }  }  public void KeyDownEventHandler(object sender, KeyEventArgs arg)  {  switch (arg.KeyData)

      {  case Keys.Left:  if (Pointer > 0)  Pointer--;  break;  case Keys.Right:  if (Pointer < Text.Length)  Pointer++;  break;

    }  }  }

    extView is an adapter class. It includes a description o themethod o rendering the text on the graphics context, as wellas the Paint method that would later be called a Decorator.

  • 8/18/2019 Design-Patterns.pdf

    66/80

    STEP Computer Academy

    66

      public class TextView : TextArea, GraphicsView  {  public Panel Parent { get; set; }  public int Offset { get; set; }

      private Font TextFont { get; set; }  public TextView(string Text, Panel parent)  :base()  {  Parent = parent;  this.Text = Text;  TextFont = new Font("Verdana", 10, FontStyle.Regular);  }  public SizeF GetBoundingRect(Graphics e)  {  return e.MeasureString(

    Text,TextFont,Parent.ClientRectangle.Width,StringFormat.GenericDefault);

      }  public void DrawText(Graphics e,Rectangle rect)  {  e.DrawString(

    Text,TextFont,Brushes.Black,new Rectangle(

    rect.X,rect.Y - Offset,rect.Width,rect.Height + Offset));

      }  public void Paint(System.Drawing.Graphics e,Rectangle updateRectangle)  {  DrawText(e, updateRectangle);  }  }

    Te BorderDecorator class is designed to add a rame tothe graphics view (a class that inherits GraphicsView). TeDrawBorder method (that actually renders the rame within thegraphics context transerred in the capacity o a parameter) andthe Paint method inherited rom the GraphicsView interace areincluded in it or this purpose. Te Paint method consistentlycalls a similar method o the aggregable graphics view (that is

    decorated by the class) and the DrawBorder method.

  • 8/18/2019 Design-Patterns.pdf

    67/80

     Lesson 2

    67

      public class BorderDecorator : GraphicsViewDecorator  {  public GraphicsView View { get; set; }  public Panel Parent { get; set; }

      public int Offset { get; set; }  public BorderDecorator(GraphicsView view)  {  View = view;  Parent = View.Parent;  BorderWidth = 2;  Offset += BorderWidth;  }  public int BorderWidth { get; set; }

    public void Paint(System.Drawing.Graphics e, Rectangle rect)  {

      View.Paint(e, View.Parent.ClientRectangle);  DrawBorder(e);  } public void DrawBorder(Graphics e)  {  e.DrawRectangle(

    new Pen(Brushes.LightGray,BorderWidth),Parent.ClientRectangle);

      }

    Te ScrollDecorator class is responsible or adding the scrollbar to the designed text view and or the response o text viewto the movement o slider on the scroll bar. For this purposethe corresponding event handlers are registered. Also, thedeclarations o helper methods were added to the class: theSetScrollRange method is necessary or changing the maximum value o the scroll bar when you change the text volume in a

    text view that is to be decorated; the SetScrollHandler methodserves to set the custom handlers to the event o changing theposition o the scrollbar slider.

  • 8/18/2019 Design-Patterns.pdf

    68/80

    STEP Computer Academy

    68

      public class ScrollDecorator : GraphicsViewDecorator  {  VScrollBar VScroll { get; set; }  public GraphicsView View { get; set; }

      public Panel Parent { get; set; }  public int Offset { get; set; }  public int ScrollPosition { get; set; }  public ScrollDecorator(GraphicsView view)  {  View = view;  Parent = View.Parent;  VScroll = new VScrollBar();  Parent.Controls.Add(VScroll);  Parent.Resize += Parent_Resize;  Parent_Resize(this, new EventArgs());

      }  public void SetScrollHandler(ScrollEventHandler handler)  {  VScroll.Scroll += handler;  } void Parent_Resize(object sender, EventArgs e)

      {  VScroll.Location =new Point(Parent.ClientRectangle.Width - VScroll.Width - View.Offset,View.Offset);  VScroll.Height = Parent.ClientRectangle.Height - View.Offset*2;  }

      public void ScrollTo(int location)  {  ScrollPosition = location;  Paint(View.Parent.CreateGraphics(),View.Parent.ClientRectangle);  }  public void SetScrollRange(int max)  {  VScroll.Maximum = max;  }  public void Paint(System.Drawing.Graphics e, Rectangle rect)  {  View.Paint(e, View.Parent.ClientRectangle);

      }  }

    Te text o class o the main application orm is shown below.Behavior o the support user interace (click handler o the windowmenu items) and the text change event handler were added intoit. Change in the maximum value o the scroll bar is a reaction

    to the event handler. Tis handler is taken into the MainForm

  • 8/18/2019 Design-Patterns.pdf

    69/80

     Lesson 2

    69

    class text, since ScrollDecorator may potentially be attached toany view. Tis action depends on the application context.

      public partial class MainForm : Form  {  public GraphicsView View { get; set; }  BorderDecorator BorderDecor;  ScrollDecorator ScrollDecor;  public MainForm()  {

    InitializeComponent();this.BackColor = mainPanel.BackColor = Color.White;View = new TextView("Hello world", mainPanel);this.KeyPress += (View as TextView).KeyPressEventHeandler;

    this.KeyDown += (View as TextView).KeyDownEventHandler;this.KeyPress += MainForm_KeyPress;BorderDecor = new BorderDecorator(View);ScrollDecor = new ScrollDecorator(BorderDecor);(View as TextArea).TextChanged += MainForm_TextChanged;ScrollDecor.SetScrollHandler(ScrollHandler);

      }  void ScrollHandler(object sender, ScrollEventArgs e)  {

    View.Offset = e.NewValue;Repaint(this, new PaintEventArgs(mainPanel.CreateGraphics(),

    mainPanel.ClientRectangle));  }  private void RecountScrollMaximum()  {  int max = (int)(View as TextView).GetBoundingRect(

    mainPanel.CreateGraphics()).Height;  ScrollDecor.SetScrollRange(max);  if (ScrollDecor.ScrollPosition > max)  ScrollDecor.ScrollTo(max);  }  void MainForm_TextChanged(object sender, EventArgs e)

      {  RecountScrollMaximum();  }  void MainForm_KeyPress(object sender, KeyPressEventArgs e)  { 

  • 8/18/2019 Design-Patterns.pdf

    70/80

    STEP Computer Academy

    70

     Repaint(

    mainPanel,new PaintEventArgs(

    mainPanel.CreateGraphics(),

    mainPanel.ClientRectangle));  }  public void Repaint(object sender, PaintEventArgs e)  {  Image img = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);  Graphics DC = Graphics.FromImage(img);  DC.Clear(BackColor);  BorderDecor.Paint(DC, ClientRectangle);  e.Graphics.DrawImage(img, 0,0);  DC.Dispose();  img.Dispose();

      }  private void mainPanel_Resize(object sender, EventArgs e)  {  Repaint(

    mainPanel,new PaintEventArgs(

    mainPanel.CreateGraphics(),mainPanel.ClientRectangle));

      }

      private void Open_Click(object sender, EventArgs e)  {

      OpenFileDialog dlg = new OpenFileDialog();  dlg.Multiselect = false;  dlg.Filter = "Text fles|*.txt";  if (dlg.ShowDialog() == DialogResult.OK)  {

      (View as TextView).Text = System.IO.File.ReadAllText(dlg.FileName,Encoding.Default);  RecountScrollMaximum();  mainPanel.Invalidate();  }  }  private void Exit_Click(object sender, EventArgs e)  {

      Application.Exit();  }

  • 8/18/2019 Design-Patterns.pdf

    71/80

  • 8/18/2019 Design-Patterns.pdf

    72/80

    STEP Computer Academy

    72

    Let’s consider all classes: ■ Window1 is a main application window through which

    the program management will be perormed. ■ Plan is an object o this class. It describes how long and

    how much water should be poured over the plants. ■ Ihardware is an interace that includes a watering method.

    It takes the Plan class object into the arguments. By means othis method, we will start the process o watering the plants.

     ■ Hardware is a class that is responsible or work with thedevices, which perorm the process o watering the plants.Since we do not have such devices, we will see the MessageBox.

     ■ ProxyHardware is a class perorming the transit ocommands to the class that is engaged in the operation odevices. HardwareProxy object executes conditional testing.

    The data receipt

    TemperatureObtain a plan

    To be poured

    Start the process

    l

    For minutes

    Date

    Enter 

    The data receiptwatering process watering process

  • 8/18/2019 Design-Patterns.pdf

    73/80

     Lesson 2

    73

      Hardware hard = null;  public void Watering(Plan a)

    {if (hard == null)

    {hard = new Hardware();}

    if ((a.Litters / a.Interval.TotalMinutes) < 1){  MessageBox.Show("Error: too low pressure");}else if ((a.Litters / a.Interval.TotalMinutes) > 4){  MessageBox.Show("Error: too low pressure");}

    else{  // Call the equipment operation.  hard.Watering(a);  }

    }

  • 8/18/2019 Design-Patterns.pdf

    74/80

    STEP Computer Academy

    74

  • 8/18/2019 Design-Patterns.pdf

    75/80

     Lesson 2

    75

     ■ DayWeather is a special class. Its objects store the weatherdata and the time when the data was recorded.

     ■ FileWork is a class that encapsulates all the work includingthe recording or downloading the weather data to the hard disk.

     ■ Calculating is a class incorporating an object that willbe engaged into the design o Plan objects considering thecollection o objects, which contain inormation about theweather or every day.

    /// /// Estimation of the plan for the last three days/// /// Collection of data on the weather for the past days/// Today’s time/// Watering planpublic Plan Calc(List a, DateTime date){  for (int i = 0; i < a.Count; i++)  {  if (a[i].Date == date && i>2)  {  int Dt = a[i].Temperature +

    a[i - 1].Temperature +a[i - 2].Temperature;

      Dt = Dt / 3;  int tim = Dt / 2;  Plan P= new Plan();  P.Interval = new TimeSpan(0, 0, tim, 0);  P.Litters = Dt;  return P;  }  }

      MessageBox.Show("Forecasting error");  Plan P2 = new Plan();  P2.Litters = 2;  P2.Interval = new TimeSpan(0, 0, 1, 0);  return P2;}

  • 8/18/2019 Design-Patterns.pdf

    76/80

    STEP Computer Academy

    76

     ■ FacadeCalculateSystem is a class providing the directionalinterace o operation with the system o storage and calculationo the climate data.

    class FacadeCalculateSystem{  private List Days;  private FileWork flework;  private Calculating Calul;

      public FacadeCalculateSystem()  {  flework = new FileWork();  Days = flework.Load();

      if (Days == null)  {  Days = new List();  flework.Save(Days);

      MessageBox.Show("The weather file was missing");  }  Calul = new Calculating();  }

      ///   /// Method adds the weather data for the day.

      ///   /// The needed day  /// Temperature of this day  public void AddDay(DateTime Date, int Temperature)  {  DayWeather Day = new DayWeather();  Day.Date = Date;  Day.Temperature = Temperature;  Days.Add(Day);  flework.Save(Days);

      }

      ///   /// Method receives a plan by date  ///   /// The day on which the plan is needed /// Action plan for the garden sprinkler  public Plan GetPlan(DateTime Date)  {  return Calul.Calc(Days, Date);  }

    }

  • 8/18/2019 Design-Patterns.pdf

    77/80

     Lesson 2

    77

    When entering the temperature into the base, the programoperation algorithm is perormed in the ollowing way:

    A user enters the greenhouse temperature value intothe program, the window translates this query to theFacadeCalculateSystem class that creates the DayWeatherobject rom the data, writes a new object to the collection andsaves the collection into a file.

    Enter temperature

    data

    Start the process of

    watering the plants

    USER

  • 8/18/2019 Design-Patterns.pdf

    78/80

    STEP Computer Academy

    78

    When a user tries to initiate watering, the ollowing algorithmis executed.

    Window1 class object sends a request to theFacadeCalculateSystem object by calling the GetPlan() method.Te Facade class redirects this task to the Calculating classobject that perorms calculation and returns the Plan classobject. Afer that, FacadeCalculateSystem also returns Planto the application window class. Ater completion o theabovementioned operation the Window class sends a request

    to the ProxyHardware class in order to make it to perormthe actions described in the plan. Te Proxy object rechecksthe data, and i everything is OK, it redirects the call to theHardware object perorming the logical operations o watering.

  • 8/18/2019 Design-Patterns.pdf

    79/80

     Lesson 2

    79

    11. Homework assignment

    Your homework assignment is to develop three modelso applications. Each o them must implement at least oneo the structural design patterns considered in the course othis lesson. Each model should be executed in the orm o asingle class diagram showing the structure o classes used by

    this model, as well as relations o these types o data.You should implement one o the developed models (optional)

    as a running application.

  • 8/18/2019 Design-Patterns.pdf

    80/80