28 Kasım 2008 Cuma

Decorator Pattern in Python


Our next step in DP is Decorator pattern, as u know Python also has some decorator options you can apply to your programs by @ sign. But if you want to apply decoration to classes in object level you have to change the stuff a little bit. I always thought that Java's IO library is very confusing, you create a FileInput class then you put it in a BufferReader and etc. When i read the Decorator chapter in Head First i realized that the Java IO API is using that pattern there. Well why do you need decorator pattern? Lets go from IO API example :
1. You have a normal reader
2. You need a reader that converts the input to lowercase, so what you do is create a new UpperReader
3. You need now a reader that converts input to a sha1 sum , what you do is create a Sha1Reader
4. You need a reader that converts input to uppercase sha1sum , what you do is create a Sha1UpperReader
5. The 4. item can be removed if you used the decorator pattern

Shortly, decorator pattern wraps an object and change its flow before or after the target operation. For the example above you can change the incoming input or process it to sth else.

Here is the implementation i wrote in Python and put on my personal github repo : LINK

A sample usage of above can be like that :

  1. def deco():

  2. from pyalgorithm.dp.decorator import *



  3. print "The normal file reader content"

  4. n = NormalFileReader("some.txt")

  5. print n.read_content()



  6. print "Sha1 sum of the read info"

  7. sh =DecoratoSha1Reader(

  8. NormalFileReader("some.txt")

  9. )

  10. print sh.read_content()



  11. print "Sha1 sum but with upper cases"

  12. up = DecoratoUpperFileReader(

  13. DecoratoSha1Reader(

  14. NormalFileReader("some.txt")

  15. )

  16. )



  17. print up.read_content()



The output is sth like that:

The normal file reader content
Hey im the content!!!

Sha1 sum of the read info
5fd77bd8e4f80ec432c71a09033a7ef51de60448
Sha1 sum but with upper cases
5FD77BD8E4F80EC432C71A09033A7EF51DE60448


Well, it is the end of the today's pattern "decorator man". The post will be a good reference for me when forget the things :)

Hiç yorum yok: