Tarefapatterns

22
M. Lozano Aparicio, Valter H. Goldberg Jr {josemachino, valtergoldberg}@gmail.com Professor: Marcelo S. Pimenta Disciplina: Engenharia de Software CMP-102 Instituto de Informática Universidade Federal do Rio Grande do Sul (UFRGS) Caixa Postal 15.064 91.501-970 Porto Alegre RS Brazil Design Pattern: study and application Sumário Design Pattern: study and application............................................................................................. 1 GoF Pattern ..................................................................................................................................... 3 Part 1 Description of Design Pattern: Observer pattern .............................................................. 3 Other Names ............................................................................................................................ 3 Problem.................................................................................................................................... 3 Solution.................................................................................................................................... 3 Participants .............................................................................................................................. 3 Implementation ........................................................................................................................ 4 Consequences .......................................................................................................................... 5 known uses .............................................................................................................................. 6 Related patterns ....................................................................................................................... 6 Part 2 Use of Pattern: Observer Pattern ..................................................................................... 6 Part 3 Discussion: Observer Pattern .......................................................................................... 11 Not GoF ........................................................................................................................................ 13 Part 1 Description of Design Pattern: Intercepting Filter .......................................................... 13 Problem.................................................................................................................................. 13 Solution.................................................................................................................................. 13

Transcript of Tarefapatterns

Page 1: Tarefapatterns

M. Lozano Aparicio, Valter H. Goldberg Jr

{josemachino, valtergoldberg}@gmail.com

Professor: Marcelo S. Pimenta

Disciplina: Engenharia de Software – CMP-102

Instituto de Informática – Universidade Federal do Rio Grande do Sul (UFRGS)

Caixa Postal 15.064 – 91.501-970 – Porto Alegre – RS – Brazil

Design Pattern: study and application

Sumário

Design Pattern: study and application............................................................................................. 1

GoF Pattern ..................................................................................................................................... 3

Part 1 Description of Design Pattern: Observer pattern .............................................................. 3

Other Names ............................................................................................................................ 3

Problem .................................................................................................................................... 3

Solution .................................................................................................................................... 3

Participants .............................................................................................................................. 3

Implementation ........................................................................................................................ 4

Consequences .......................................................................................................................... 5

known uses .............................................................................................................................. 6

Related patterns ....................................................................................................................... 6

Part 2 Use of Pattern: Observer Pattern ..................................................................................... 6

Part 3 Discussion: Observer Pattern .......................................................................................... 11

Not GoF ........................................................................................................................................ 13

Part 1 Description of Design Pattern: Intercepting Filter .......................................................... 13

Problem .................................................................................................................................. 13

Solution .................................................................................................................................. 13

Page 2: Tarefapatterns

Participants ............................................................................................................................ 13

Implementation ...................................................................................................................... 14

Consequences ........................................................................................................................ 14

Related patterns ..................................................................................................................... 15

Part 2 Use of Pattern: Intercepting Filter ................................................................................. 15

Part 3 Discussion: Intercepting Filter ........................................................................................ 20

Part 1 Description of Design Pattern: Software as Service ....................................................... 21

Problem .................................................................................................................................. 21

Solution .................................................................................................................................. 21

Structure................................................................................................................................. 21

Implementation ...................................................................................................................... 21

Consequences ........................................................................................................................ 22

Known Uses ........................................................................................................................... 22

Page 3: Tarefapatterns

GoF Pattern

Part 1 Description of Design Pattern: Observer pattern

Other Names

Dependents, Publish-Suscribe

Problem

Context

The pattern occurs when we have cooperating classes and we need to maintain the

consistency between related objects.

Solution

Define a one to many dependency between objects so that when one object changes state,

all its dependents are notified and update automatically.

Structure

Participants

Subject

Knows it observers

Provides an interface for attaching and detaching Observer objects

Observer

Defines an updating interface for objects that should be notified of changes in a subject

Concrete subject

Stores state of interest to concrete observer objects

Sends a notification to its observers when its state changes.

Page 4: Tarefapatterns

Concrete observer

Maintains a reference to a concrete Subject object. Stores state that should stay consistent

with the subject’s.

Implements the observer updating interface to keep its state consistent with the subject’s

Implementation

1. Mapping subjects to their observers.

Store references to them explicitly in the subject.

In the case of many subjects and few observers use an associative look-up (e.g., a hash

table) to maintain the subject-to-observer mapping.

2. Observing more than one subject.

It's necessary to extend the Update interface. Thus, the subject can pass itself as a parameter in

the Update operation, thereby letting the observer know which subject to examine.

But what object actually calls Notify to trigger the update? Here are two options:

a. Have state-setting operations on Subject call Notify after they change the subject's state.

Pro: Don’t call Notify in the subject

Con: Inefficient when multiple operations

b. Make clients responsible for calling Notify at the right time.

Pro: avoiding needless intermediate updates

Con: Can cause errors if the client forget to call Notify

3. Dangling references to deleted subjects. Deleting a subject should not produce dangling

references in its observers. One way to avoid dangling references is to make the subject notify its

observers as it is deleted so that they can reset their reference to it.

4. Making sure Subject state is self-consistent before notification.

This rule can be violate unintentionally when Subject subclass operations call inherited

operations. You can avoid this pitfall by sending notifications from template methods in abstract

Subject classes.

5. Avoiding observer-specific update protocols: the push and pull models.

push model: the subject sends observers detailed information about the change, whether

they want it or not.

pull model: the subject sends nothing but the most minimal notification, and observers

ask for details explicitly thereafter.

Page 5: Tarefapatterns

6. Specifying modifications of interest explicitly. You can improve update efficiency by

extending the subject's registration interface to allow registering observers only for specific

events of interest. When such an event occurs, the subject informs only those observers that have

registered interest in that event.

7. Encapsulating complex update semantics. We use the ChangeManager which purpose is to

minimize the work required to make observers reflect a change in their subject. ChangeManager

has three responsibilities:

It maps a subject to its observers and provides an interface to maintain this mapping.

It defines a particular update strategy.

It updates all dependent observers at the request of a subject.

There are two specialized ChangeManagers. SimpleChangeManager which is fine when multiple

updates are not issue, DAGChangeManager which ensure observer receives just one update.

8. Combining the Subject and Observer classes which lets define an object that acts as both a

subject and an observer.

Consequences

1. Minimal coupling between subject and observers.

2. Subject doesn't care how many interested objects exist

3. Dynamic addition and removal of observers can cause unexpected updates and can be worst

when update protocol provides no details on what changed in the subject.

Page 6: Tarefapatterns

known uses

In user interface toolkits:

In Smalltalk Model/View/Controller (MVC).MVC's Model class plays the role of Subject, while

View is the base class for observers.

InterViews: defines Observer and Observable (for subjects) classes explicitly.

Andrew Toolkit: calls them "view" and "data object," respectively.

Unidraw: splits graphical editor objects into View (for observers) and Subject parts.

Related patterns

ChangeManager is an instance of the Mediator pattern. The Singleton pattern would be useful

here.

Part 2 Use of Pattern: Observer Pattern

Context Description:

Description of the work: Area of application is a module of SIGEA system. The company uses

this system for manage their information and support decision. The problem is that when the

stock is under the limit, there doesn’t exist an alert for the administrator to buy that product

again. That situation makes that company losses clients because sometimes the company doesn’t

have the product just in time.

The system was created for commercial companies that need to manage the different areas of the

company. It has the following modules: Sale, purchase, accountancy, and logistic.

The web page from this system is http://www.itesoperu.com/

This system implements parts of ERP. And the module is localized in the inventory control

http://www.slideshare.net/oxygen024/erp-functionalmodules

This module keeps track of stock levels and inventory, return and adjustments.

One of us has the opportunity to see this software, and one of the things that the manager said

was that problem. And we present the model of how the system make the part of logistics.

Page 7: Tarefapatterns

Pattern Adaptation:

In this case the observer pattern is applied because there is a necessity of notify to the other users

like administrator logistic operator that are the observers, and the subject is the module that

manage the datastore of the part of logistics. The diagram altered will be in this way.

Page 8: Tarefapatterns

Now we show how we tried to simulate in java. The first two images is the subject, or the

datacontroller that take the parameter of the subject. The class CModel implements the methods

of notify and add listeners. The class CVentPrueba which simulates the process of sale

registering an specific product, and notify to the other listeners.

Page 9: Tarefapatterns

The next images are the observers which are CAdministrador and CAlmacenero. When these

classes are notified, check if the current stock is less than the minimum and send a message.

Page 10: Tarefapatterns

Then, we show how are they in the main; This could be localized when a product is sold to a

customer.

Page 11: Tarefapatterns

Finally, we executed in the console and we show in the following image. We insert to registers

and in the second register the product is notified to the observers that it is less than the minimun.

Part 3 Discussion: Observer Pattern

Justifications:

First, we were going to do the implementation of the paper [Burmeister and Helke 2012] , but we

realized that for implementing it need more level of abstraction and knowledge of the actor

model. Thus, we continue searching more documents and we found these interesting papers that

introduce the aspect oriented programming within the design pattern implementation. In the

Page 12: Tarefapatterns

papers [Mcheick and Qi 2012], [Bhanage and Babar 2012], [Axelsen et al. 2009] mentioned how

aspect oriented programming influence in the implementation of observer pattern.

In the article of Yan [Mcheick and Qi 2012] is proposed the observer pattern applied in the

publish subscribe architecture. This is used in distributed systems. Thus, we don’t consider this

case because it requires knowledge of distributed system and create a distributed system to

applied what has been done there.

Package templates a mechanism for code modularization is used in [Axelsen et al. 2009] work

for develop a reusable observer pattern and presents how groovy implements an observer pattern

using package template. But this doesn’t give a situation case for implementing observer pattern

so we tried to review modules of systems that need to apply it. And we used one specific part of

module of SIGEA which is system used in a Peruvian company. We simulate the part of register

a sale of a product. We follow the implementation of one site.1

Bibliography

Mcheick, H. and Qi, Y. (2012). Combination of connectors with loosely coupled architecture

based on aspect-oriented computing. In 2012 International Conference on Communications and

Information Technology (ICCIT) , pages 97–101

Burmeister, R. and Helke, S. (2012). The observer pattern applied to actor systems: A

TLA/TLC-based implementation analysis. In 2012 Sixth International Symposium on

Theoretical Aspects of Software Engineering (TASE) , pages 193–200.

Bhanage, D. A. and Babar, S. D. (2012). Analyzing effect of aspect oriented concepts in design

and implementation of design patterns with case study of observer pattern. International Journal

of Engineering .

Axelsen, E. W., Srensen, F., and Krogdahl, S. (2009). A reusable observer pattern

implementation using package templates. In Proceedings of the 8th workshop on Aspects,

components, and patterns for infrastructure software , ACP4IS ’09, page 3742, New York, NY,

USA. ACM.

1 http://www.vogella.com/articles/DesignPatternObserver/article.html

Page 13: Tarefapatterns

Not GoF

Part 1 Description of Design Pattern: Intercepting Filter

Problem

Context

Presentation-tier request handling mechanism receives many different types of requests,

which require varied types of processing.

Solution

Use an Intercepting Filter as a pluggable filter to pre and postprocess requests and

responses. A filter manager combines loosely coupled filters in a chain, delegating control to the

appropriate filter. In this way, you can add, remove, and combine these filters in various ways

without changing existing code.

Structure

Participants

FilterManager: manages filter processing. It creates the FilterChain with the appropriate

filters, in the correct order, and initiates processing.

FilterChain: it is an ordered collection of independent filters.

Page 14: Tarefapatterns

Filter: We can have many filters such as Filter1, Filter2,...These are mapped to a target.

The FilterChain coordinates their processing.

Target: it is the resource requested by the client.

Implementation

We use strategies for the implementation. One of them is the custom strategy which is according

to the developer. For these it can use the decorator pattern. Disadvantage of this is that not

provide flexible postprocessing.

Another option is the standard filter strategy, base filter strategy, template filter strategy and web

service handling strategies which has the custom SOAP filter and JAX- RPC filter. These two

filter strategy differentiates that in SOAP filter you write a custom handler to fulfill participant

responsibilities.

Standard filter strategy provide for the wrapping of request and response objects in a standard

and portable way.

Base filter strategy serves as common superclass for all filters. Common features can be

encapsulated in the base filter and shared among all filters

Template filter strategy use base filter strategy to dictate the general steps that every filter must

complete, while leaving the specifics of how to complete that step to each filter subclass.

Consequences

Centralizes Control with Loosely Coupled Handlers: Filters provide a central place for

handling processing across multiple requests, as does a controller. Filters are better suited

to massaging requests and responses for ultimate handling by a target resource, such as a

controller. Additionally, a controller often ties together the management of numerous

unrelated common services, such as authentication, logging, encryption, and so forth,

while filtering allows for much more loosely coupled handlers, which can be combined in

various combinations.

Improves Reusability: Filters promote cleaner application partitioning and encourages

reuse. These pluggable interceptors are transparently added or removed from existing

code, and due to their standard interface, they work in any combination and are reusable

for varying presentations.

Declarative and Flexible Configuration: Numerous services are combined in varying

permutations without a single recompile of the core code base.

Information Sharing is Inefficient: Sharing information between filters can be inefficient,

since by definition each filter is loosely coupled. If large amounts of information must be

shared between filters, then this approach may prove to be costly.

Page 15: Tarefapatterns

Related patterns

Front Controller

The controller solves some similar problems, but is better suited to handling core

processing.

Decorator [GoF]

The Intercepting Filter is related to the Decorator, which provides for dynamically

pluggable wrappers.

Template Method [GoF]

The Template Method is used to implement the Template Filter strategy.

Interceptor [POSA2]

The Intercepting Filter is related to the Interceptor, which allows services to be added

transparently and triggered automatically.

Pipes and Filters [POSA1]

The Intercepting Filter is related to Pipes and Filters.

Part 2 Use of Pattern: Intercepting Filter

We present two case study of this pattern.

Context Description 1:

The research of employment and unemployment is done in seven regions of Brazil (Belo

Horizonte, Distrito Federal, Fortaleza, Porto Alegre, Recife, Salvador, São Paulo) which search

indicators of unemployment, income and occupations by economic activity. The foundation

Seade and Dieese2 show the information since 1985. It is done a statistic planning. After that, it

is applied a questionnaire which follows a unique methodology. The questions are standard, but

the answers have different granularity degree. This is a problem because they can not compare

the answers immediately. They have to process the data to make it comparable.

Pattern Adaptation 1:

We thought that for this problem, it can be applied Intercepting filter because we are going to

preprocess the answers that the server receives and put in a level that can be comparable. We

show our solution in the diagram above. We applied three filters, one is the selector filter that

will filter the state to redirect the information if it is the question or answer. Then is applied the

filter for standard question or standard answer which are going to normalize and return the

values.

2 http://www.dieese.org.br/analiseped/ped.html

Page 16: Tarefapatterns

Context Description 2:

Description of the work: Area of application is a module of Pirwa Hostel Web system. Pirwa

Hostel has a web system implemented in php. The system makes reservations. The website is

http://www.pirwahostelsperu.com. The problem is related to the control flow which is not

centralized. Everything is validated in each component, which makes to have repetitive code.

This is according to one of the members’ experience.

Pattern Adaptation 2:

We tried to simulate the process like this web page3 said about vending a product. In our case we

are doing something similar like selling. In our case we present the solution in the following

diagram.

3 http://www.slideshare.net/ProdigyView/intercepting-filters-design-pattern

sd if

UIDiesse CFilterStateSelector CFilterStandarAnswerCFilterStandarQuestion Questionario

Request Questions()

requestQuestionofState()

requestData()

responseData()

Standardized()

responseQuestionofState()

returnResponse()

SaveAnswer()

RequestToSaveStateData()

Standardized()

SaveData()

Page 17: Tarefapatterns

In the implementation we used the ProdigView Framework4. This framework implements the

most common patterns like observer, adapter, and filter pattern. So, we inheritance the methods

of PVObject. We centralized the filters in the Book button of the image.

4 http://www.prodigyview.com/framework

Page 18: Tarefapatterns

First we have to filter, if selected any room then, we have to validate the person data. And after

that we have to validate if the person has money in his count. Thus, we simulate that will be used

for this case. We create the class creserva.php. Then we add the class filters one for room, other

for data person.

Page 19: Tarefapatterns
Page 20: Tarefapatterns

Part 3 Discussion: Intercepting Filter

Commentary:

This design pattern was defined in the Core J2EE Patterns and is widely used in pre-and

post-processing queries of Web Services. There are strategies for implement pattern Intercepting

Filters such Standard Filter Strategy and Custom Filter Strategy.

The Standard Filter Strategy is more flexible, but this is only available from the Java

Servlet 2.3 specification. The Custom Filter Strategy is less powerful, because it can´t

encapsulate the request and response objects in a standard and portable. In order to have control

of the output of the filter should employ a flow control mechanism. To implement the custom

strategy can be used Decorator pattern [GoF] to gather around the filters request processing logic

core.

Using the Intercepting Filter enables the addition of filter processing requests improve

logic without requiring a redesign of the application. This guarantees the possibility that the

system could be reconfigured in a less time and with less cost.

Justifications:

Reviewing the literature of the applicability of the intercepting filter we check that is

applied to improve MVC in the part of Front Controller as [Ying 2005] mentions. Also some

frameworks like Lion5 implemented this functionality, just to be applied. However we don´t

have access to the paper that is in the Chinese library. Thus, we pick a case study of a web

system and we present how will be the pattern is used. Also a case study of standardization relate

to questionare.

Bibliography

LI Ying, WANG Li-fang, JIANG Ze-jun, 2005 .Improving MVC Software Architecture by

Intercepting Filter pattern. Link: http://en.cnki.com.cn/Article_en/CJFDTOTAL-

WXYJ200501022.htm

5 https://code.google.com/p/lion-framework/wiki/InterceptingFilter

Page 21: Tarefapatterns

Part 1 Description of Design Pattern: Software as Service

Problem

Context

When a person or organization is building an application whose model, control or view aspects

must be refreshed based on dynamic circumstances or instances in which specialized

functionality of the application must be delivered.

Solution

Saas is a model of software delivery in which the manufacturer is responsible for the

daily technical operation of the software provided to the clients (including maintenance and

support), while the clients enjoy the full benefits of the software from remote locations.

Structure

Involves deploying different aspects of the model, view and control components of an

application to multiple physical locations.

Implementation

First a user identifies his requirements for consuming computing resources. Then request

a service. The service does the computer request, it found the functionality and returns

information which is provided to the user . this pattern becomes very interesting when multiple

users employ the resources and implementers have capabilities that do not exist for their non-

SaaS counterparts. First, the functionality provider can detect and act on patterns in runtime

interactions. Second, a provider may want to consider scaling the system in the backend to

handle large numbers of requests.

Page 22: Tarefapatterns

Consequences

Create additional complexity in supporting computer resources for large number of users.

Difficult to implement and to police authentication in software licensing.

Software may have dependency on a internet connection.

Denial of service attacks can be a threat.

The user might be subjected to occasional outages when service upgrades or other events

take place on the provider side.

Personal security risks.

Known Uses

Postini, Inc, a email company begun to use similar SaaS pattern. Apple’s iTunes music

application is one hybrid approach of SaaS pattern. Adobe Systems recently launched a service

that allows people to manually create small numbers of PDF documents online. And Google

continues to expand its SaaS offerings.