Wednesday 9 May 2007

Singleton Pattern - A practical use

The other day I was watching I program I think it was BBC 1 about how people's credit and detail card details are being stolen and wrongfully used when pin numbers land in hands of the wrong people.

I thought of how patterns can help in tackling this problem, I reached our Bible – GOF book, scanned through all the patterns. Guess what!

The singleton pattern I think can help tackle the problem . I this blog I share my idea about how singleton pattern is be used here.

The Singleton pattern ensures that there is one and only one instance of class and provides a global point of access to that instance.[Copper, p39]. Singleton

Every account when have one pin at a time. Using singleton pattern, systems can be designed where the uniqueness that password is limited at a given time say each week.

Suppose the banking system has an Account Class which generates pin numbers, the Account Class should only create one pin number and also destroy on a weekly basis. All subsequent pin numbers created should never be similar to the one created before on that account.

This will provide uniqueness to the weekly pin number being generated.

Saturday 7 April 2007

Anti Patterns

In this class - 3rd April, Dr Sri introduced Antipatterns. At first I thought this Antipattern thing was unacceptable, given the Introduction to Patterns and the patterns we have covered so far.

I went through Jane's notes too and the links there on. Well, after studying and examining the views of those that support antipatterns, I got a very different view altogether.

I do not intend to discuss details of antipatterns in this blog, since this is one of the questions the coursework.

However, of members that may be interested in what I have researched on regarding antipatterns, I will post this information after submission of the coursework.

Hope people will still be interested.

Tuesday 27 March 2007

Strategy Pattern

In this blog I look at the Strategy Pattern, its applicability, strengths and weakness, and how it differs from other patterns

Strategy Pattern defined

The strategy pattern defines a family of algorithms, encapsulate each one, and make them interchangeable. [1] This pattern lets the algorithm vary independently from clients that use it. The different algorithms will be appropriate at different times.

The main benefit of Strategy Pattern is that if one wants to add a new algorithm, it can be added easily without disturbing the application using the algorithm.

Strategy is also known as Policy.


When to apply the Strategy Pattern

The Strategy pattern is used in the following situations:

Encapsulate various algorithms to do more or less the same thing. This makes the program easier to maintain. For example, one can simply add or remove an algorithm without affecting the rest of the application.

Strategy is also used where one needs one or several algorithms to be implemented in an application dynamically.

Strategy helps avoid exposing complex and algorithm-specific structures to the rest of the application. This feature again makes application maintenance much easier.

With Strategy Pattern multiple conditional statements are reduced. Instead of using multiple conditional statements, algorithms are encapsulated each in its separate object. This reduces the number of loops in the application therefore enhancing the performance of the application.

Just like the decorator pattern, Strategy provides alternatives to sub-classing. This therefore overcomes some of the weaknesses associated with inheritance.

When applying Strategy Pattern please watch out!!!

Despite at advantages of Strategy Pattern, it has the following limitations

As the number of algorithm increases in an application, the number of objects also may increase. This can be a set back to the strategy pattern as too many objects are introduced in the application.

Just a thought, in case there are many algorithms, can the program spend too much time trying to work out which algorithm to use? Or is best for the given context? If the answer this is yes, then I think it’s not a good idea to have too many algorithms as the application take too long trying to work out the best suited algorithm.


Differences between Strategy and other patterns
In this section I compare Strategy pattern with other patterns namely: State, Flyweight, Decorator and Composite

Strategy Vs State

State Pattern activates several states of an object, whereas strategy can only activate one of the algorithms. Therefore the scope of the Strategy is limited only to algorithms with no reference to states of a given object.

Strategy Vs Flyweight

Flyweight provides a shared object which can be used in multiple contexts simultaneously, whereas strategy focuses only on one context.

Decorator Vs Strategy

Decorator pattern changes the skin of the object while Strategy changes the gut of an object. Strategy is a better choice in situations where the component class is intrinsically heavyweight, thereby making the decorator pattern too costly to apply.

According to the GOF, by extending the number of strategies from just one to an open-ended list, we achieve the same effect as nesting decorator recursively.

Composite Vs Strategy

Composite is used to combine a strategy to improve efficiency.

It ought to be noted that State, Strategy, Bridge and Adapter have similar solution structures. They all share elements of the “handle/body” idiom. They differ in intent of course; that is they solve different problems.

It becoming more clear, the more patterns we cover the more I have come to realise that no one pattern is an island. Last week I thought the Decorator Pattern had it all. This the Strategy is seemingly more interest, well, lets see what next week has. One lesson I have learnt is to first cover all the patterns and them make a judgement. But still it will be hard I think to come out will the best pattern.

They all look good, do not they???

References:

[1] Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
Design Patterns,
Elements of Reusable Object-Oriented Software,
(1995)
Addison-Wesley
Page 315 - 323

Sunday 25 March 2007

Decorator Pattern

Decorator Pattern

In short the Decorator Pattern allows responsibilities to be assigned to an object without sub-classing and add the responsibilities dynamically to the object. Decorators provide a flexible alternative to sub-classing for extending functionality.

Decorator Pattern addresses the limitation of inheritance. Inheritance adds behaviour to an object at compile time where decorator provides a new behaviour to an object at runtime.

Inheritance can be used where the sub classes can be predicted while with the decorator such predictability is not required.

The main advantage of the Decorator pattern is that it avoids extensive sub-classing.

Other advantages of using the Decorator Pattern include:

The ability to develop more elegant programmes as too many sub-classing are removed. This further makes it easy to maintain the application.

The Decorator also provides the capability to add new functions to an object without affecting other objects. All other objects remain intact during developing or during maintenance of the application.

Decorator Pattern makes it possible to easily add or remove responsibility from an object dynamically.

Decorators can be recursively nested without any other objects being able to tell the difference, allowing a near infinite amount of customization.

Make ones code more flexible. Decorating is more flexible than plain, old static inheritance. With the decorator pattern, one can add, any number of decorators to a particular component.

The Decorator pattern keeps things simple. When using the decorator pattern, one does not have to complex classes that consider every possible scenario. With the Decorator Pattern, one only needs to design a simple abstract class and then decorate the class as necessary. One can further develop new concrete decorators without disturbing the original design of the application.


Demerits of the Decorator pattern

Identity crisis problem: Decorators wrap themselves around components. They therefore change the identity of the component onto which they wrap themselves. The resulting component is not therefore the same as the original component. One therefore needs to be careful about object identity whenever reference is made to one of the decorated components.


The other problem is Object Critters.
Even with the decorator pattern, one can still have too many classes, especially concrete decorator classes. This is the same problem the inheritance has.[1]


In this section the differences between Decorator Pattern and other patterns namely: Adapter, Proxy, Composite, and Strategy is examined


Decorator Vs Adapter

The Adapter Pattern provides a different interface to the object it adapts, whereas decorator changes the object’s responsibilities or simply provides an enhanced interface to the subject.

When compared to Adaptor Pattern, the Decorator Pattern is more transparent to the client. The other difference between the Adapter and Decorator Pattern is that the Decorator Pattern support recursive composition, which is not possible with pure Adapter Pattern.

Decorator Vs Proxy Pattern

Proxy Pattern and Decorator Pattern have different purposes but similar structures. The main similarity between the two is that they both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward the request.

Proxy pattern however, controls access to the object whereas a decorator adds additional responsibilities to an object.

Decorator Vs Façade Pattern

Façade pattern provides a way of hiding a complex class, whereas decorator adds function by wrapping a class.

Decorator Vs Composite pattern

Composite and Decorate when examined closely have similar structure diagrams, which re-enforces the fact that both rely on recursive composition to organize an open ended number of objects. Further examination of the Decorator and Composite Patterns shows that decorators can be viewed as a delegate Composite with only one component.

The Composite Pattern’s focus is not on embellishment but on representation. This makes the intent of both patterns complementary. [2]




[1]

Barry Burd and Micheal P Redlich
Decorator Pattern
(2007)
http://javaboutique.internet.com/tutorials/decorator/index-4.html
Accessed: 22nd March 2007

[2] Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
Design Patterns,
Elements of Reusable Object-Oriented Software,
1995
Addison-Wesley
Pages 219 -220

Friday 16 March 2007

Adapter Pattern

In this week’s lecture we covered the Adapter Pattern. In this blog I give an overview of the Adapter Pattern and my opinion about it.

An Adapter Pattern is one of the structural patterns by GOF. Its used in situation where you have one class that you wish to reuse, but the application interface does not match the class interface.[1] The Adapter is therefore used to convert the application interface to the existing class interface. Put simply, the Adapter maps the interface of one class to that of another.

I especially like the example of an electric socket that was used in class to explain the adapter pattern.

How the Adapter pattern works

A Client wants to invoke the method request() in the Target interface. Since the Adaptee class has no request() method, it is the job of Adapter to convert the request to an available matching method. Here the Adapter converts the method request() call into the Adaptee method specificRequest() call. The Adapter does this conversion for each method that needs adapting.

The two types of Adapter Patterns are:

1. Object Adapter Pattern(contains an instance of the class it wraps)
2. Class Adapter Pattern (using multiple inheritance)

From the class discussion, I think this is one of the most important patterns in software development.

With the Adapter Pattern, one does not have to change local objects, the adapter takes care of the job.

Beside, the adapter pattern reduces the creation of excessively heavy and low performance remote objects. Therefore lighter programmes can be developed.

Since adapter separated responsibilities along class lines, one produces a design that is easy to debug and code the in easier to read.

Like other patterns, once created, adapters can be used over and over again saving both effort and time.


Though adapter pattern provides the benefits highlighted above, I have noted a few issues with them.

I think one must be carefully when using the Adapter pattern. When the design of the Adapter is poor, even if the applications/interfaces that the adapter intends to adapt are good, the design of the adapter may negatively affect the overall performance of the classes involved.

The scope of adapting that an adapter does also needs to be considered. Rather than improving performance between the adapted class the adapter may compromise functionality of one of the classes hence affecting performance of both classes whenever they interface.


References

[1]
Dan Becker,
Design Networked Applications in RMI Using the Adapter Pattern,
A guide to correctly adapting local Java objects for the web
(5/01/99)
http://www.javaworld.com/javaworld/jw-05-1999/jw 05networked.html?page=1
Accessed: 16th March 2007

[2]
Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
Design Patterns,
Elements of Reusable Object-Oriented Software,
(1995)
Addison-Wesley
Page 139 – 150

[3]

James W Copper,
Java Design Patterns,
(2000)
Addison Wesley
Page 71 - 79

Monday 12 March 2007

The Abstract Factory

Task 1 – Abstract Factory

In this lecture we looked at the Abstract Factory design pattern. In this blog I discuss my understanding of the Abstract Factory

Definition 1

Abstract Factory is a set of related abstract classes, the Abstract Factory pattern provides a way to create instance of those abstract class from a matched set of concrete subclasses. This pattern is useful for allowing a program to work with a variety of complex external entities such as different windowing systems with similar functionality.[1]

Definition 2

Abstract Factory pattern can also be defined as a design pattern that provide an interface for creating families of related or dependent objects without specifying their concrete classes.[2]

The link to reference [2] provides a good structure of the Abstract Factory together with the code.

In Abstract Factory, the client does not know (or care) about which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from its general usage.

A good example of when the Abstract Factory should be used is when a system needs to support multiple look-and-feel for the user interface for example Windows 9x, Motif, and Macintosh. The same application will have different look and feel under different platforms without the need to change the core of the application.

A non software illustration of Abstract Factory design pattern

In the sheet metal stamping equipment used in the manufacture automobiles, the stamping equipment is an Abstract Factory. It creates auto body parts. The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. Through the use of rollers to change the stamping dies, the concrete classes produced by the machinery can be changed within three minutes. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

Advantages of using Abstract Factory

  • The Abstract Factory isolates the concrete classes from the abstract classes that generated them. Because of the isolation of classes, you can change or interchange
    The product class families freely.

  • Further, since one generates only one kind of concrete class, this system avoids from inadvertently using classes from different families of products.


    Disadvantages of using Abstract Factory
  • There is nothing to prevent some derived classes from having
    additional methods that differ from the methods of other classes.


    Related Patterns

    1. Factory Method
    2. Singleton: Concrete Factory classes are usually implemented as Singleton classes

    Task 2

    Examining the Coursework and critiquing it.

    The lecturer asked us to examine the Coursework and critique it.

    The coursework has something for every one, both programmers and non-programmers. Task 1 can easily be handled by both programmers and non-programmer. Programmers may not have problems with Task 2 especially if Task 1 was well handled.

    However, in case Task 1 is not efficiently do, results in Task 2 may be badly affected. To attempt Task 2 would require one to have do Task 1 pretty well. It would also be difficult to do Task 2 without doing Task 1.

    It also put to use the skills previously learned for example the use of UML. One can therefore apply skills previously learned.

    The blog is quite an interesting one. From the blogs I have done so far and from commenting on other people’s blogs, I have learnt a lot about Design Patterns. It also makes the subject interesting. The blog is funny!!

    To understand patterns even better, the course work requires/covers anti-patterns. Being a subject about Patterns I had not expected to find Anti-patterns being mentioned at all. However studying patterns and anti-patterns gives an appreciation of the two concepts. One can there for better understand them.

    Task 3 further cements the understanding of Design Pattern by allowing students form complete patterns from a list of incomplete ones. This gives a practical dimensional to the subject which would have rather been too theoretical.

    However the word limit on the essay seems to be tight, given the kind of discussion this will be.

References:


[1] Mindspring.com
Overview of Patterns
(2007)
http://www.mindspring.com/~mgrand/pattern_synopses.htm#Abstract%20Factory
Accessed 2nd March 2007

[2] Data and Object Factory
Abstract Factory
http://www.dofactory.com/Patterns/PatternAbstract.aspx
(2007)
Accessed 2nd March 2007

Sunday 4 March 2007

Critiquing the GOF cataloquing technique for Abstract Factory design pattern

This lecture’s tasks were:

Task1:

Selecting any one to the GOF Design patterns; and criticizing its cataloguing technique.

Below I criticise the GOF cataloguing technique of the Abstract Factory design pattern.


The Abstract Factory has been catalogued consisting of the following elements; Name, Intent, Also Known As, Motivation, Applicability, Structure, Participants, Collaborations, Consequences, Implementation, Sample Code, Knows Use, and Related Patterns.

This cataloguing technique gives a birds view of what the pattern is about, what it does and results of using the pattern. Such detailed information gives confidence to the user as all the information they need about the pattern is available.

Further it save the designer time as they would know how and where to apply the pattern rather than finding out such information from scratch.

By giving the applicability of the pattern further reassures the pattern user that the pattern under consideration will produce the results it claims to yield, and that the pattern has be used and proven to work.

The Consequence element in cataloguing the pattern is quite useful, since it adequately addresses the trade offs or benefits of using the pattern before it is used. Therefore the user is given a chance to carefully weigh the usage of the pattern.

While as the cataloguing technique has the above advantages, it does not come without flaws. Below are some of the disadvantages of the cataloguing technique of Abstract Factory.

The GOF have argued that the name of a pattern should be unique. That is a pattern is solely known by one name only. However, including the Also Known As element in the cataloguing technique compromises the uniqueness of a pattern name.

By explicitly showing where the pattern is used can reduce the designer innovativeness as they may not take time to think of new and better situations in which to apply the pattern. Designer may restrict themselves to applying the pattern to only known uses.

Since the Structure of the pattern is given; especially in form of a UML diagram, there seemed to be no need to further give a sample code for the pattern. This code may be left out as it can be worked out from supplied UML diagram. Users are given a choice to implement/ code the pattern in any language of their choice - of course an Object Oriented language. This removes the fuss of having the code the same pattern in say Java, Smalltalk, C++ and others.

The inclusion of Motivation and Applicability in the cataloguing technique is irrelevant. The Applicability section includes situation in which the pattern is usable and also represents the context part of the pattern. The Motivation section on the other hand provides a scenario which consists of a problem and a context in which the pattern can be used. This two elements can therefore be shown as one, that is either as Applicability or Motivation.


Task 2:

This task requires finding out one other Design Pattern apart from those supplied by the GOF



Typed Links Design Pattern

This is one of the MobileUI Design Patterns developed by Patterns in Interaction Design, www.welie.com. The Patterns in Interaction Design catalogue their patterns as: Problem, Context. Solution; Rationale; Example; and Known Uses.

The Typed Links Design Pattern with its elements.

Problem:
Users need to know what they are selecting

Context:

Since WML only has links there is no way to tell whether the link is used to go down a hierarchy or a link to a real service or a link that leads out of the portal.

Solution:
Use special prefixes to distinguish several types of links.
Use a prefixed link to indicate the type of the link. A "+" can be used to indicate a category, a ">" to indicate that it is an outgoing link. Other types may include payments or help.

Rationale:
The prefix shows meta information about the link destination. The meta information, even unconsciously, helps users to understand what they are doing.

Example:
To show a category a "+" is used and to show an outgoing link a ">" is used.

Knows uses: wap.tutch.nl

www.welie.com.