Vous êtes sur la page 1sur 80

Lesson No.

2
Structural
patterns

Contents
1. Concept of structural pattern. . . . . . . . . . . . . . . . . . . . . . . . 4
2. Adapter pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

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


2.2. Causes of pattern occurrence. . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4. Results of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
2.5. Example of a practical pattern application. . . . . . . . . . . . . . . . 12

3. Bridge pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15


3.2. Causes of pattern occurrence. . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.4. Results of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17

4. Composite pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.2. Causes of pattern occurrence. . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.4. Results of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23
4.5. Example of a practical pattern application. . . . . . . . . . . . . . . . 23

5. Decorator pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

5.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


5.2. Causes of pattern occurrence. . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.4. Results of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29

6. Facade pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

6.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36


6.2. Causes of pattern occurrence. . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.4. Results of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39
6.5. Case example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

7. Flyweight pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
7.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
7.2. Causes of pattern occurrence. . . . . . . . . . . . . . . . . . . . . . . . . . . 42
7.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
7.4. Results of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .46
7.5. Case example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

8. Proxy pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

8.1. Pattern purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50


8.2. Causes of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
8.3. Pattern structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
8.4. Results of pattern use. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53
8.5. Case example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

9. Analysis and comparison of structural patterns . . . . . . . 57


10. Examples of practical application of structural patterns . 59
11. Homework assignment. . . . . . . . . . . . . . . . . . . . . . . . . . . 79

STEP Computer Academy

1. Concept of structural
pattern
Based on the definition of information systems, it is obvious
that any software solution operates some block of data. When
analyzing them we obtain some information that allows us to
make business and regular decisions on management of the
Information System itself.
The analysis of data assumes that it should be arranged in a
structure. On the one side, it allows to identify different data
(logically distinguish them), on the other side to organize
elementary values into structured objects and their combinations.
Data structuring is necessary to reflect the concepts used in
the analysis and display the relationships formed between the
objects in the process of their occurrence.
Object-oriented approach provides us with a wealth of tools
for description of structured concepts and reflection of their
relationships. However, the organization of structure that connects
concepts into a working system is critical for the effective use
of information systems, as well as maintenance obtained in the
result of the product development process.
In general, design patterns reflect the best models of making
decisions on engineering problems, which stand the test of time
and practice. Structural patterns provide models of organization
of data into structures, which solve the problem of organization
of data management in the most efficient way. It is understood
that the data may be presented not only with atomic values, but
also with all the objects existing within our application.
4

Lesson 2

Then we will review basic structural patterns, which are


considered to be the best practices of software development
by the world community.

STEP Computer Academy

2. Adapter pattern
2.1. Pattern purpose

In order to make the material easy-to-understand, as well


as to simplify the presentation, we will use the following
terminology that is specific with respect to the considered
problem:
Client is a class that uses (aggregates) an adaptee class.
Adapter is a class that transforms the interface of adaptee class
to the interface expected by the client.
Purpose of the Adapter design pattern is to cast (adapt)
the interface of adaptee to the interface that is expected by
the client.

2.2. Causes of pattern occurrence

The following problem is widely met: there is some class


in a set of tools that is to be used in order to solve a problem,
not specific for the structure of class. For example, we have
declared a data type called IPEndPoint that describes the concept
of network appliance. It is authorized for such properties as
IP-address, MAC-address and host name, which are used in
order to perform an engineering analysis (for example, trace
a package movement). The analysis is performed by a class
that aggregates a variety of objects of the IPEndPoint type.
This class is called NetView. However, we tend to implement a
graphical representation of the process and the result of analysis.
6

Lesson 2

In addition it should be displayed in the main window of our


application. The problem is that the NetView class has not an
interface that is specific for the object of graphics system. That
is why it cannot be used by window class in order to perform
rendering. We cannot rewrite (change a source code and a
structure, respectively) the NetView class in order to make it
suitable for the needs of application, because it is a part of the
used types of dll-library provided by the third parties. Or we
just do not want to overload the class structure, since it is
critical for any tasks of 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 inheritance
and define a rendering interface of the NetView type of data by
overriding the methods specific for the component of graphics
system.
Such a mediator class is commonly called an adapter.

STEP Computer Academy

2.3. Pattern structure

Structure of the Adapter pattern is shown in the above


diagram.
Involved elements:
Client is a class that uses some auxiliary data types and
expects them to have a standard interworking interface (interface
of application) described by the Target class.
Target is a class containing an interface expected by the
client.
8

Lesson 2

Adaptee is a class that is required for client operation,


but its interface differs from the one expected by the client.
Adapter is a class casting the Adaptee class interface to
the Target class interface.
In the above structure, an interface casting is carried out
due to the fact that the Adapter class inherits both the Adaptee
and Target classes, and therefore, it has both their interfaces.
Then the Adapter class casts method calls, which are specific
for the Target class interface, to the calls of the appropriate
methods of the Adaptee class interface.
The below sequence diagram shows that calls of methods
of the Adapter class object are reduced to the calls of methods
of the object of its base class.

Also it is possible to implement the Adapter pattern in an


alternative way. Its structure is shown in the below diagram.

STEP Computer Academy

In contrast to the previous structure, the Adaptee and


Adapter classes are not related, but they are involved in an
association relationship, i.e. the Adapter class aggregates the
Adaptee class.
Thus, the Adaptee class interface is casted to the Target class
interface due to the fact that the method calls of the Adapter
class object, which are specific for the Target class interface,
are casted to the appropriate methods of the Adaptee class
object, encapsulated in the Adapter class. The below sequence
diagram demonstrates this process.

10

Lesson 2

2.4. Results of pattern use

The main positive result of use of the Adapter design pattern


is a possibility to cast a class interface to the interface expected
by application in a quite flexible manner and without changing
the structure of class. It is necessary both in terms of elimination
of the redundancy of the types structure and modularity of
applications being created.
Redundancy plays a negative part when we need to reuse
a written code (for example, in another application). This
code is called a reusable code. The reusable code creation is
considered to be a good practice, because it reduces the cost
and increases the speed of the development. Also it increases
the flexibility and scalability of applications being created due
to the modular structure of finished application.
It is much easier to expand an application by adding new
types than to completely recreate some of the modules.

11

STEP Computer Academy

2.5. Example of a practical pattern


application

We will consider a specific example of use of the Adapter


pattern that includes an application managing a companys
turnover. In order to control products, we will describe the
Product (product/item) data type that will be organized into
a collection of products by means of the ProductsCollection
class.
Also, our application controls other aspects of activity of
a trading company. We will omit them in order to provide a
proper transparency of the example.
A data backup may be used to solve almost any task. In order
to implement a possibility of its creation, we decided that all the
data should be exported to separate xml-files. For this purpose
we have implemented the XmlIO class reading and recording
an Xml-document. Its object is encapsulated with the window
class of our application. In order to record a collection of
products into a file, we have created the ProductXmlIOAdapter
class. It encapsulates a collection of products, implements the
casting of this collection to an xml-document, as well as this
xml-document to the collection.
Thus, we implement the function of recording the collection
of items into an xml- file. At the same time, we do not change
the structure of source data type, but eliminate a structure
redundancy that might appear as a result of provisioning
the Product class with additional functionality. Redundancy
elimination is necessary, because the Product data type may
be used in order to cast the product information obtained
from the database to an object representation. This gives a
12

Lesson 2

possibility to perform a further analysis. While executing


all these steps, the redundancy of type structure may create
additional difficulties. Also, such a modular structure adds
flexibility, when maintaining a project, and makes it possible
to use (create) a reusable code.
The following class diagram shows the above described
application.

13

STEP Computer Academy

14

Lesson 2

3. Bridge pattern
3.1. Pattern purpose

Purpose of the Bridge pattern is to separate an abstraction


and its implementation in order to make them capable to vary
independently.

3.2. Causes of pattern occurrence

Usually, if an abstraction (an abstract class) may have a few


specific implementations, they use inheritance in order to
define a number of classes of a similar or matching interface.
Abstract class defines an interface for its descendants. This
interface is implemented by them in a variety of ways.
However, this approach is not always flexible enough and has
some weak spots. They may lead to the code redundancy and
create additional difficulties while maintaining a project. All
of that may significantly increase its price. Single inheritance
of abstraction interface, executed by a specific class, connects
implementation and abstraction in a direct manner. This
creates difficulties in the process of further modification
(extension) of implementation and also does not allow us to
reuse abstraction and its implementation separately from each
other. Implementation seems to become firmly associated
with abstraction.
The Bridge design pattern places an interface and its
implementation into different hierarchies. This allows us
to separate an interface from the implementation and use
15

STEP Computer Academy

them independently, as well as to combine any options of


implementation with various refined options of abstraction.

3.3. Pattern structure

The Bridge design pattern is represented with the following


structural elements:
Abstraction defines an interface of abstraction and contains
an implementors object defining an interface of implementation.
Implementor defines the interface for classes of
implementation. Implementors interface does not have to
conform to the abstraction interface. Interfaces defined by
abstraction and implementor may be quite different that is
flexible. In general, implementor should identify basic operations,
which serve as a base for high-level logic of abstraction.
RefinedAbstraction extends an interface of certain
abstraction.
ConcreteImplementor is a class that implements an
implementors interface and defines its particular implementation.
Abstraction and implementor form a bridge together. It
connects the refined abstraction and concrete implementation.
Structure of the Bridge design pattern is presented below in
the class diagram.

16

Lesson 2

3.4. Results of pattern use

A main benefit provided by the Bridge design pattern is that


abstraction is separated from the implementation in terms of logic
and structure providing a code with extra flexibility. Also, the Bridge
pattern application improves such a qualitative characteristic of
the code as extensibility, because abstraction and implementor
pertain to different hierarchical structures. Thus, it becomes
possible to extent an implementation regardless of abstraction,
and vice versa.
Another reason to use the Bridge design pattern is the fact
that it allows us to hide implementation details from the client,
i.e. from the application using an abstraction. It allows the client
not to depend on a particular type of implementation in one
case or another.
17

STEP Computer Academy

Example of a practical pattern application


We are going to consider a specific example of the mixed graphics
editor (editor that allows us to edit raster and vector graphics in a
collaborative manner, i.e. within a single representation) in order
to understand the use of the Bridge design pattern.
A model of application assumes an availability of some graphical
representation operating by several abstract figures. The interface
of interaction with such figures is described by the Figure interface
playing a part of abstraction in this example.
The interface of implementor is determined by the FigureImp
interface, from which VectorFigure and RasterFigure classes are
inherited, respectively. VectorFigure and RasterFigure classes
describe the implementation of rendering the vector and raster
figures.
After determination of implementation we can refine the
abstraction describing an interface of a specific figure (e.g.,
ellipse). After that, you can associate a refined abstraction with
a concrete implementation, for example, to define VectorEllipse
and RasterEllipse classes, describing the vector and raster ellipses,
respectively.
The model of application described above is shown below.

18

Lesson 2

19

STEP Computer Academy

4. Composite pattern
4.1. Pattern purpose

The Composite pattern is designed to represent objects in


the tree structure in the part-whole hierarchies.

4.2. Causes of pattern occurrence

The Composite pattern exists, because a tree structure is


quite common and it is often used for the management of data
of regular structure. This structure implements a part-whole
hierarchy, assuming that an element of some data composition
may be either an elementary member, or a similar composition.
The simplest implementation of such a structure with a
recursive containment system may be expressed as the system
of types. It contains classes describing the basic components
and classes, which will be used as containers for elementary
components.
However, this approach has a serious disadvantage. A code
using these classes must separately process the elements and
their containers, even if in most cases they are processed in the
same way. This considerably complicates the implementation
of application.
The Composite pattern offers a recursive structure that
allows us not to make decisions on the method of processing
the separate elements of the whole data collection.
The key to understanding the nature of the Composite
pattern is a definition of the abstract interface that is identical
20

Lesson 2

to elementary components and their containers. Since container


and elementary components are related and share a common
user interface, container may be an element of another similar
container creating a comfortable regular (recursive) structure.

4.3. Pattern structure

Component describes an interface to objects and their


compositions; implements the basic behavior that is specific
for the individual elements and their compositions; defines an
interface to access the composition elements and to manage
these elements; also it determines an interface to access a parent
element of the recursive structure.
Leaf defines a single element of the composition and
describes the behavior of primitive (basic) elements of the
overall structure.
Composition determines the behavior of components
containing child elements, encapsulates the child elements,
implements the control operations and the access to child
elements defined by a component interface.
Client manages the elements of composition by means
of the component interface.
The Composite pattern structure is presented below in the
form of a class diagram that is shown in the figure.

21

STEP Computer Academy

22

Lesson 2

4.4. Results of pattern use

The Composite pattern application helps to simplify the


organization of elements in a containment structure of data and
eliminates the code redundancy in the process of implementation
of this task. Also, the Composite pattern makes the client
object simpler and allows it to process basic components and
their compositions in the same way in virtue of their unified
interface, determined by the class-component.
The Composite pattern simplifies the process of adding
the new components. Regardless of whether new classes are
elementary components or compositions, they will work
with a structure that had already existed at the time of their
creation. In other words, there is no need to change the client
while creating the new components.

4.5. Example of a practical pattern


application

We will consider the use of the Composite design pattern


on the basis of organization of a variety of elements of the
graphical user interface having a regular structure. In other
words, any window may include not only controls, but also
the other windows. Windows may be simplistically described
as the compositions of controls.
In order to organize the Composite pattern for a certain
problem, we declare the UIElement abstract class. It describes
the element of graphical user interface and defines the interface
of basic behavior of the graphical interface element and the
control interface of child elements of the composition.
23

STEP Computer Academy

Basic behavior of the element of graphical user interface


includes Hide, Paint and Show methods. They implement an
ability to display an element, redraw its graphical representation
and hide it, respectively.
Add, GetChild and Remove methods are defined in order to
control the access to child elements of the composition. They
allow us to add a new child element, receive it and remove an
element from the composition, respectively.
The Control class describes a control element that acts as a
primitive element of Composite being implemented by us. It
implements basic behavior. The Window class is a composition
of controls. However, it also implements basic behavior, since
it has a basic graphical representation.
The Application class plays a part of client associated with
a certain window, i.e. it uses an object of the Window class
and an interface described by the UIElement class.
Model of the described application is shown in the class
diagram in the figure below.

24

Lesson 2

25

STEP Computer Academy

5. Decorator pattern
5.1. Pattern purpose

The Decorator pattern purpose is to implement a possibility


to add a dynamic functional to the object, as well as to allocate
responsibility for the implementation of separate functions
between the individual classes.
The Decorator pattern is an alternative to the inheritance
in terms of the functional extension of objects.

5.2. Causes of pattern occurrence

Subdivision of responsibility for the implementation of


separate operations between the individual classes is a very
popular approach, since it creates a structure, each class of
which encapsulates the control logic with duties assigned to
it. Both a modularity simplifying the development and an
opportunity to close the access to operations for the class are
of equal importance.
Inheritance is one of the methods allowing the allocation
of responsibilities for implementation of a common task
between different classes. However, this approach is inflexible,
because in case of inheritance the added function is statically
assigned for all descendants of this class. In order to create
different types (with different functionality), you must execute
inheritance in all the possible combinations.
Decorator allows us to combine the object functionality
according to its internal logic in a flexible manner and
26

Lesson 2

dynamically change the object functionality at the runtime,


since the addition of function is reduced to the creation of a
component object of a particular class.

5.3. Pattern structure

The structure of the Decorator pattern is represented by


the following elements:
Component is an abstraction of element that will be
assigned with the scenery (composition). Of course, the
scenery shall be understood to mean not a visual design,
but an addition of the specific functions. Component contains
a declaration of abstract operation. Later, decorator will add
new features 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 perform
a function encapsulated in a component, and then adds a new
functionality.

27

STEP Computer Academy

Since Decorator is a special case of component (inherits


the Component), then another Decorator may be used as an
encapsulated component. It allows us to perform a recursive
sequence of the calls of redefined operation with gradual
accumulation of functional (as shown above in the sequence
diagram).

28

Lesson 2

ConcreteDecoratorA and ConcreteDecoratorB represent


private decorator implementations of the component.
Structure of the Decorator design pattern is illustrated in
the class diagram below.

5.4. Results of pattern use

As mentioned above, the use of pattern allows us to implement


the allocation of responsibilities for the performance of difficult
task among several classes in a more flexible manner than
when using the inheritance.
On the other hand, the Decorator design pattern allows us
to avoid redundancy of the class hierarchy, because it is not
necessary to create classes, which would include functionality
of the all necessary combinations.
29

STEP Computer Academy

Example of practical pattern application


We will consider the example of model of the text editor
with html-syntax highlighting.
It is supposed to use the class of text view in order to
implement the view logic of text information to a user. The
model of text view organization is given below.

30

Lesson 2

On the one hand, the text view class (TextView) is inherited


by the class of specific view implementation in the form of
text area (the TextArea class) supporting the editing. In order
to maintain a possibility of extension of functional of the text
view, we have declared the TextDecorator class. Actually, this
class is implemented by the Decorator pattern. We create a
concrete implementation of the TextDecorator class in order
to implement the possibility of html-syntax highlighting. It
encapsulates the logic of implementation of 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 image
having the size of the client area of application, for which the
graphics context is initialized. Object of the graphics context of
the created image is transmitted to the Paint method of object
of the HtmlHighlightDecorator class. The last calls the Paint
method of object of the TextArea class and, subsequently, the
DrawColoredText method that is responsible for the highlighted
text rendering. The sequence of calls is shown in the sequence
diagram, given below.

31

STEP Computer Academy

Thus, after returning the control to the Paint event handler of


window class, the highlighted text syntax will be rendered in an
image created by the handler. The last thing we do is rendering
the resulting image on the graphics context of window, to which
the text view is related.
32

Lesson 2

Then, such implementation will allow us to add and remove


a variety of decorating effects associated with the text editor in
a quite flexible manner. For example, line numbers connecting
lines for matched elements, as shown in the figure above.
It is enough to declare several decorators and add them to the
text view in a window class, to which the text view is related.
A generalized model is shown below.

33

STEP Computer Academy

34

Lesson 2

6. Facade pattern
The Facade pattern is largely designed for encapsulation
(hiding) of content and division of logical parts to independent
subsystems. In the real world the Facade pattern structure
is applied in many situations. A good example is a fast-food
restaurant, where you just come to the cashiers desk and order
the meals. As a rule, you are not interested in the detailed
structure of such a quick service restaurant. However, there is
also an office in this restaurant. You may come there and refer
to it according to the narrow interface (for example, to become
a regular client). Thus, the restaurant gets two subsystems,
which depend on each other in minimum. Together they are
added up to one big system.
User

subsystem
Restaurant

subsystem
Office
Cashiers desk

Reception desk

Accounting
department

Kitchen

Support
services

Warehouse
Cleaning

35

Personnel
Department

Marketing

STEP Computer Academy

6.1. Pattern purpose

Purpose of the Facade pattern is a definite structuring of


classes into subsystems. You may access each of them through
a single interface. When constructing application architecture,
it is advisable to divide it into separate subsystems, which
should be as independent as possible.
Each part of program (a subsystem) will have its own Facade
class, by means of which the management of this part of
program will be performed.

6.2. Causes of pattern occurrence

It is very difficult to design and build a large application


at once. Architects have solved this problem by splitting the
programs into smaller subsystems. It allows us to build any
part of program without focusing on other aspects of it and
then to continue with writing the next subsystem. If you build
independent systems, it is possible to get a safe substitutability
of its components or whole subsystems. If you get an independent
subsystem, you can use it in other projects again. Finally, if
a team of programmers includes more than one person, it is
possible to commit a task to write a separate subsystem to each
of them and then just connect them into a whole application.
However, you had to reread a lot of documentation about
this structure and understand how to use it in order to take
advantage of an unfamiliar subsystem. The Facade pattern was
created to solve this problem. It means that each subsystem will
have its own class. This class is a sort of the subsystem saver.
It will be easy to interact with the structure through this class.
36

Lesson 2

37

STEP Computer Academy

6.3. Pattern structure

The Facade pattern assumes the existence of a subsystem


in the program, for which the Facade class is created. The
execution of operations from the subsystem classes is triggered
by means of the Facade class.
Also, it should be noted that the clients (subsystem users)
should not have access to the subsystem classes.
If it is possible, all of the subsystem objects should be kept
in the Facade class. When calling a method from the Facade
object by the clients, it begins to work with the subsystem
classes.

38

Lesson 2

The above example is not usual. The Facade pattern may


incorporate more or less than three classes within a subsystem.
Object of the Facade class is able to call the methods of
elements of the subsystem, configure them, assign values to
their properties, and so on.
Optionally, the Facade class must hold a subsystem class
objects in storage.
It is possible to provide access to subsystem objects through
the Proxy pattern. Sometimes, programmers do the Facade
class static in order to make it possible to address this class
from any point of the program.

6.4. Results of pattern use

It is easier to build the program starting with writing the


separate independent subsystems, not the entire application at
once. In addition, we get a finished block of program that may
be used in other applications. It is also possible to replace one
of the subsystem components without disturbing the overall
structure of application.
If we create a separate Facade class for every subsystem, it
is easier to use such a system, as all the work of this structure
is encapsulated (hidden) in the Facade class.
It is possible to obtain greater performance, flexibility and
security of the application by using other patterns along with
the Facade pattern.

39

STEP Computer Academy

6.5. Case example

Lets consider the Facade pattern using the example of


following application: a simple translator of words. For instance,
a user enters a word in Russian and gets a translation of this
word into English.
Application should provide an opportunity to work with a
dictionary of pre-recorded words (save, load) from a file. Also, this
application should be able to add new words into the text database.

40

Lesson 2

The program is provided with a subsystem designed to


work with a dictionary. Access to it will be obtained through
the Facade class object.
Diagram of classes of the application is displayed above.
A user will manage the system through the Facade class
(FacadeFileBase) that, in turn, calls objects of the subsystem.

41

STEP Computer Academy

7. Flyweight pattern
7.1. Pattern purpose

The purpose of pattern is a storage-efficient use of the


computers memory. This is achieved by means of a proper
way of operation with a large number of small objects.
In order to understand the pattern concept, it is necessary
to learn how to separate internal and external features of
the object. Internal object feature is a property that is stored
within the object. In other words, it is an instance of class that
includes a property (a variable) created inside it and stored
as long as the object is living. External feature is a property
that is transferred to the object as an argument to one method
(or a few methods). It exists as long as the method is being
performed.
The essence of pattern is to transform the internal features
into the external ones. After that it is not necessary to create
many objects, but only one that will be displayed in different
ways depending on what external properties are applied thereto..

7.2. Causes of pattern occurrence

After migration to the object-oriented programming it


becomes easier to program, because all objects seem to be real.
Of course, it is associated with a number of difficulties. When
creating a model of application, there is an urge to place objects
according to the principles of object-oriented programming. For
example, a chair consists of a seat and legs, and a seat includes
42

Lesson 2

more additional parts. If we describe such architecture in detail,


it may arise a situation, when there will be created too many
objects. Application having such a structure will suffer from
lags. What shall we do, when the required level of details is
unreachable for a computer?
Answer: It is necessary to separate logical and physical conception
of the application. In programming we can found such situations,
when one and the same entity is placed in two (or more) locations.
For example, logically we have a chair, consisting of a seat and
legs. Physically, in the program it was created an object of a leg
that appears in different locations. In order to make an object
appearing in different places, it is enough to transmit a number
of parameters to an object when calling the display method
from it. These parameters will indicate where and how to display
this element. Applying this approach when constructing the
architecture, a programmer will obtain an application that will
use computer resources in an efficient way.

7.3. Pattern structure

An object occurring in several locations at the same time is


called an opportunist. These objects are provided with access
by means of factory. The client creates objects of opportunists
using the factory. It calls a method returning the opportunist
object and receiving an object identifier that is to be returned.
Factory holds objects of opportunists (a collection, an
array or individual objects) in storage. It is important that the
objects should be created at the clients first request. As it was
mentioned above, when receiving the subsequent requests,
they should get a created object stored inside the factory.
43

STEP Computer Academy

When calling the GetObj method, a user passes an object


ID to this method. Object ID is needed if an object with such
an index has been already created. It must be returned as a
result of the method operation. However, if the object was not
created, it would be necessary to create it and record into the
factory storage. After that, it should be returned as a result of
method operation.
Further, the GetObj method is presented for review.
Classes A, B, C are inherited from the base class describing
an interface of interaction with all the types of opportunists.

44

Lesson 2

45

STEP Computer Academy

Further, the GetObj method is presented for 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 from the base class describing


an interface of interaction with all the types of opportunists.

7.4. Results of pattern use

If you apply this pattern to your application, you get significant


memory savings. The result will remain the same even if we
will take into account that when gaining access to the object,
the factory method time is lost (GetObj in this case). However,
the efficiency of storage will be obtained only if the objects
will contain a minimum number of internal properties when
46

Lesson 2

the external ones will be transferred in response to the calls.


External properties should be defined using the algorithms.
The basic idea of pattern is to use memory in an efficient way
by means of the computational performance.
Access to the objects of opportunists should be obtained
through the factory methods only, since it will add flexibility
and a possibility to customize an object within the factory
methods.
You should apply the pattern, when there are a lot of objects
in your application and it is possible to describe their condition
by means of the external features, and the external features
may be described and assigned by calculation.

47

STEP Computer Academy

7.5. Case example

Lets consider a console application that will display and


calculate the result of battle between two armies.

48

Lesson 2

Human, Motor and Tank classes differ from each other by


the values of the internal properties and the method displaying
a fighting unit to the screen.
The FactoryUnit class object will hold in storage from
zero to three objects in the form of Unit within the ListUnits
collection that was specially created for this purpose. Classes
of clients will be able to get access to the object by calling the
method from the factory and passing the list object to it. This
object will indicate a particular Unit that should be returned
as the result of method call.
The Player class will use factory in order to obtain and display
the objects properties. However, all of the objects of players
will actually use 3 instances of classes of Unit descendants
only, and this should provide a storage-efficiency.
Program is a major class containing the Main method
and the Battle method. Program management is performed
within the Main method. The Battle method is responsible for
calculations showing the result of battle between two armies
of two players.

49

STEP Computer Academy

8. Proxy pattern
The Proxy pattern is often called a substitute pattern. Further,
the main class that will be discussed is referred to us as a
substitute or a proxy. Both terms are correct and describe the
same class/object.
Proxy is an object providing a transit access to another object.
Substitute is an object that externally looks in the same way
as the main one, but it has no internal functionality.
A substitute or a proxy object externally looks in the same
way as the object represented by it. However, all of its internal
functionality is a kind of a tunnel providing the client classes
with a possibility to access the main objects.
Additionally, a substitute or a proxy object may be called
a stand-in object.

8.1. Pattern purpose

The purpose of pattern is the creation of system providing


an access to the object through a special substitute object.

Client

Substitute

Target class

This allows us to achieve greater flexibility in the operation


with a target class object.
50

Lesson 2

If the target class object will occupy a lot of space after its
creation and there is no guarantee that the object will be needed
in the application, it is possible to create a target object when
the client calls the method of the substitute object at the first
time. It will speed the application performance up if the object
will not be used. However, if the object is created, then it will
not be so harmful for the program performance.
Such a system of access will allow us to use a target class in
the same, but more protected way (it is possible to perform
various checks of the accepted parameters within a substitute).
For example, if a target class is a calculator, it just adds two
parameters into the method arguments and performs basic
mathematical computations. Within the substitute of the
calculator class, it is possible to check that the calculator will
not be given such a task, as to divide by zero.
You can use structure of the proxy pattern in order to create
an object sent into another name space. For example, target
class is described in the name space that for some reason is
impossible (or uncomfortable) to connect. In this case we are
able to create a substitute that will be located in the needed
name space and the target class object will be created within
the substitute taken from another name space.

8.2. Causes of pattern use

Syntax and structure of the code of some programmers should


be clear for other programmers. If you build an application
using a proxy pattern in order to access the objects, check the
data within the substitute objects and execute logical operations
within the target class, then it is quite easy to explain another
51

STEP Computer Academy

programmer, where checks and basic logical operations are


executed. In general, it is fairly easy to explain the structure of
application by means of the patterns.
Perhaps, you have already seen the applications, which continue
their running after starting and only after 5 seconds or more
they begin to display an interface. It happens, because when
you start running the application, it begins to download all of
its modules immediately, creates all instances of the needed (or
needless) classes for the application operation. You can create
a substitute of a large object when launching an application in
order to partially solve this problem. Substitute is only a model
that is not as large as the target object, and therefore it is created
in a faster manner. A large object will be created only if it is
necessary. A necessity appears when the client classes will work
with an object substitute that will forward all the requests to
the newly created target object.

8.3. Pattern structure

The Proxy pattern assumes the presence of object (hereinafter


referred as a target class) that will be accessed via a specially
created object substitute.

52

Lesson 2

However, a substitute object should not externally differ


from the target object class, because both classes must be
inherited from a single interface.
In the below example, the Math target object is created along
with the substitute object, because the Math class is not large
and it will be created in a quicker way.
The example shows how to use a substitute object in order
to perform various checks before the immediate transfer of
data to the target class.

8.4. Results of pattern use

When providing the access to the pattern through the


substitute object, we obtain an additional level of work with
the target object. At this level, we can deal with optimization
creating target objects as long as they will be used. You can
perform a data validation before transferring it to the target
object. You can also enter the logging of access to an object
within the substitute object (for example, calculate how many
times the summability method has been called in the calculator).
53

STEP Computer Academy

8.5. Case example

Lets consider the structure of informational shop application


in order to better understand this pattern. The Shop class is
available within the application architecture. It is accessed
through the ProxyShop class. The Shop class has a method
that accepts a line containing the key and then returns a line
with information, if possible.
54

Lesson 2

The ProxyShop class protects the Shop class from the


possibility of its brutforsing. Also, the Shop object is created
when it is required in the program only. In other words, it is
created when someone tries to get information using the key.
The class diagram of this application is displayed below.

55

STEP Computer Academy

The GetInfo method of ShopProxy performs the object


creation and access control.
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";
}

The GetInfo method of 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;
}
}

56

Lesson 2

9. Analysis and comparison


of structural patterns
You have already studied all of the structural patterns:
Adapter is a pattern that allows us to adapt an object to
a different interface in order to gain access to it. For example,
there is an Operation1 method within the object. We need
to make it to be called OperationA. Purpose of the Adapter
pattern is to edit an access interface to the target object.
Bridge is a pattern that allows us to separate the abstraction
and implementation, when there is an objects hierarchy described
in an abstract manner. In addition, a specific system hierarchy
will be implemented later. Purpose of the Bridge pattern is
to build independent abstraction and implementation, and
provide the client with abstraction, by means of which it will
be able to manage the implementation.
Composite is a structural pattern that builds tree objects.
The purpose of this pattern is to build a tree-like structure in
order to store the objects.
Decorator is a pattern that allows us to compose structure
in such a way that a few objects are displayed as one. The
number of internal objects may vary at a high rate.
Facade is a structural pattern that explains how to build
large applications of small independent subsystems. The pattern
purpose is to create a narrow and intuitive interface in order
to work with the subsystem.
Flyweight is a pattern that allows us to use the memory
in an efficient manner if the program has a lot of small objects
and their status may be transferred into the external properties,
57

STEP Computer Academy

which are calculated by means of the algorithms.


Proxy involves the creation of substitute object for the target
object. For this reason, it is able to provide greater flexibility,
storage-efficiency and protection.
We should select patterns considering their purpose, because
at first glance it may seem that the patterns are similar. It seems
that some of them have a similar structure. However, every
pattern has a purpose. For example, you might think the Facade
and Proxy patterns are very similar, but they are applied for
different purposes. The purpose of the Facade pattern is to
create a narrow interface for the subsystem operation. The Proxy
pattern protects the target object.
Structures of the Composite and Decorator patterns are also
very similar, but you should start with the purpose of their
application. The Composite pattern structures the objects and
the Decorator pattern allows us to create separate types of
functionality and connect them into one object.
Often people do not see the difference between the Facade
pattern and the Adapter pattern, because it seems that they
have the same purpose. This purpose is to change or modify
the interface of access to one or a few objects. However, using
the adapter we are able to work with an old interface of access
to the object and use a new one. In turn, the Facade pattern
creates a new more focused interface.
It is important to note the fact that pattern is not a standard
of the program structure. In practice, we might hear: Here
we have an architecture that is similar to the Flyweight pattern
architecture. However, different types of objects are returned
from different methods within the factory.
58

Lesson 2

10. Examples of practical


application of structural
patterns
The first example is an application that uses the Adapter
and Decorator structural patterns. An application will be a text
editor including a possibility to open a text file. However, it will
not use the controls designed for editing and provided by the
standard system of .NET Framework types (such as TextBox
and RichTextBox). Actually, the purpose of the example is to
show an approach used for organization of the control element
executing the text editing.
The Adapter pattern will be used to connect the class
performing the text control (control refers to the receipt, storage
and editing) with some graphical context that is the TextArea
class. The TextView class will perform the text rendering.

59

STEP Computer Academy

A model of connection of the text area with the graphics


context using the Adapter pattern is shown in the above diagram.
The GraphicsView interface defining a standard element
interface with a graphical view is declared.
The TextView class inherits the GraphicsView and the
TextArea.

60

Lesson 2

Further, we will use the Decorator pattern in order to design


the control element. In particular, we will determine two
decorators: the first one will perform rendering of the frame
around the text area. The second one will add a scroll bar to
the text area and execute the text view rendering with due
regard to the displacement of the scroll bar.
A general model is shown below.

61

STEP Computer Academy

After declaration of classes in accordance with the


abovementioned model, we will get a structure of classes
that is shown in the class diagram below.

62

Lesson 2

We should note that the model does not always consistent


with the implementation. Therefore an UML-diagram and a
class diagram of the finished project may significantly differ
from each other. However, general approach remains unchanged.
In order to add a class diagram to a project, we should call a
context menu of the project in the SolutionExplorer window
and select the creation of class diagrams.
It is necessary to fill the form in the following way: add
menu, bar and the Dock feature that should be set to Fill.
You should get a result that is similar to the represented one.

Menu

Bar

Further, we will consider the application code by classes


shown in the class diagram.
Below we can see a graphics interface element or an element
that may be rendered in the graphics context.
63

STEP Computer Academy

public interface GraphicsView


{
Panel Parent { get; set; }
int Offset { get; set; }
void Paint(System.Drawing.Graphics e, Rectangle updateRectangle);
}

The GraphicViewDecorator interface inherits a graphics


area. It differs by the fact that it defines the View property of
the GraphicsView type only, because the Decorator should
have a link to the view that is to be decorated.
public interface GraphicsViewDecorator : GraphicsView
{
GraphicsView View { get; set; }
}

The text area is described below. It includes methods of


processing the text that is to be added into the __text field. This
process is carried out by means of the KeyPressed window event
handler. The KeyDown event handler serves for processing
the movement of internal pointer of the text area by pressing
the Left 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;
}

64

Lesson 2

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;
}
}
}

TextView is an adapter class. It includes a description of the


method of rendering the text on the graphics context, as well
as the Paint method that would later be called a Decorator.

65

STEP Computer Academy

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);
}
}

The BorderDecorator class is designed to add a frame to


the graphics view (a class that inherits GraphicsView). The
DrawBorder method (that actually renders the frame within the
graphics context transferred in the capacity of a parameter) and
the Paint method inherited from the GraphicsView interface are
included in it for this purpose. The Paint method consistently
calls a similar method of the aggregable graphics view (that is
decorated by the class) and the DrawBorder method.
66

Lesson 2

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);
}

The ScrollDecorator class is responsible for adding the scroll


bar to the designed text view and for the response of text view
to the movement of slider on the scroll bar. For this purpose
the corresponding event handlers are registered. Also, the
declarations of helper methods were added to the class: the
SetScrollRange method is necessary for changing the maximum
value of the scroll bar when you change the text volume in a
text view that is to be decorated; the SetScrollHandler method
serves to set the custom handlers to the event of changing the
position of the scrollbar slider.

67

STEP Computer Academy

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);
}
}

The text of class of the main application form is shown below.


Behavior of the support user interface (click handler of the window
menu items) and the text change event handler were added into
it. Change in the maximum value of the scroll bar is a reaction
to the event handler. This handler is taken into the MainForm
68

Lesson 2

class text, since ScrollDecorator may potentially be attached to


any view. This 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)
{

69

STEP Computer Academy

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 files|*.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();
}

70

Lesson 2

In the result of successful code writing, we should have


an application that is similar to the one that is shown in the
image below.
It should be noted that the patterns themselves do not
provide significant benefits. The secret of a successful and
effective development is to combine patterns and apply them
where their application can deliver a positive result.

Interactivity is a sign of the availability


of a certain percentage of intellect.
This feature becomes a main feature
of communication, everything changes
and acquires new, totally different, few
ever seen shades. [edit] The degree
of interaction
The nature of interaction is reflected in
the extraverted translation of reaction
(informative cue of the internal structural
inertia) of the contractor at the systemdeterministic

Program for tracking the greenhouse climate


This application uses two patterns. They are the Proxy pattern
creating a substitute of access to a class that is engaged in
watering (working with the hardware) and the Facade pattern
creating an object of the restricted access to the computing
subsystem how much water should be poured and what
temperature should it have.
71

STEP Computer Academy

The data receipt

watering process

The data receipt

Temperature

watering process

Obtain a plan
To be poured

Date

For

Enter

l
minutes

Start the process

Lets consider all classes:


Window1 is a main application window through which
the program management will be performed.
Plan is an object of this class. It describes how long and
how much water should be poured over the plants.
Ihardware is an interface that includes a watering method.
It takes the Plan class object into the arguments. By means of
this method, we will start the process of watering the plants.
Hardware is a class that is responsible for work with the
devices, which perform the process of watering the plants.
Since we do not have such devices, we will see the MessageBox.
ProxyHardware is a class performing the transit of
commands to the class that is engaged in the operation of
devices. HardwareProxy object executes conditional testing.

72

Lesson 2

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);
}
}

73

STEP Computer Academy

74

Lesson 2

DayWeather is a special class. Its objects store the weather


data and the time when the data was recorded.
FileWork is a class that encapsulates all the work including
the recording or downloading the weather data to the hard disk.
Calculating is a class incorporating an object that will
be engaged into the design of Plan objects considering the
collection of objects, which contain information about the
weather for every day.
/// <summary>
/// Estimation of the plan for the last three days
/// </summary>
/// <param name=a>Collection of data on the weather for the past days</param>
/// <param name=date>Todays time</param>
/// <returns>Watering plan</returns>
public Plan Calc(List<DayWeather> 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;
}

75

STEP Computer Academy

FacadeCalculateSystem is a class providing the directional


interface of operation with the system of storage and calculation
of the climate data.
class FacadeCalculateSystem
{
private List<DayWeather> Days;
private FileWork filework;
private Calculating Calul;
public FacadeCalculateSystem()
{
filework = new FileWork();
Days = filework.Load();
if (Days == null)
{
Days = new List<DayWeather>();
filework.Save(Days);
MessageBox.Show("The weather file was missing");
}
Calul = new Calculating();
}
/// <summary>
/// Method adds the weather data for the day.
/// </summary>
/// <param name=Date>The needed day</param>
/// <param name=Temperature>Temperature of this day</param>
public void AddDay(DateTime Date, int Temperature)
{
DayWeather Day = new DayWeather();
Day.Date = Date;
Day.Temperature = Temperature;
Days.Add(Day);
filework.Save(Days);
}
///
///
///
///

<summary>
Method receives a plan by date
</summary>
<param name=Date>The day on which the plan is needed</param>

/// <returns>Action plan for the garden sprinkler</returns>


public Plan GetPlan(DateTime Date)
{
return Calul.Calc(Days, Date);
}
}

76

Lesson 2

Enter temperature
data

Start the process of


watering the plants

USER

When entering the temperature into the base, the program


operation algorithm is performed in the following way:
A user enters the greenhouse temperature value into
the program, the window translates this query to the
FacadeCalculateSystem class that creates the DayWeather
object from the data, writes a new object to the collection and
saves the collection into a file.

77

STEP Computer Academy

When a user tries to initiate watering, the following algorithm


is executed.
Window1 cl ass obj e c t s ends a re quest to t he
FacadeCalculateSystem object by calling the GetPlan() method.
The Facade class redirects this task to the Calculating class
object that performs calculation and returns the Plan class
object. After that, FacadeCalculateSystem also returns Plan
to the application window class. After completion of the
abovementioned operation the Window class sends a request
to the ProxyHardware class in order to make it to perform
the actions described in the plan. The Proxy object rechecks
the data, and if everything is OK, it redirects the call to the
Hardware object performing the logical operations of watering.

78

Lesson 2

11. Homework assignment


Your homework assignment is to develop three models
of applications. Each of them must implement at least one
of the structural design patterns considered in the course of
this lesson. Each model should be executed in the form of a
single class diagram showing the structure of classes used by
this model, as well as relations of these types of data.
You should implement one of the developed models (optional)
as a running application.

79

Vous aimerez peut-être aussi