Wrap around pattern is not listed in in GOF book but is very useful for problem like below
- Loop construct for e.g do while/while/for loop
- Stopwatch around some code.
- Wrap checked exception with run time exception
- Initialization and cleanup for eg Threadpool creation/destruction or file open/close etc
- Adding context info to threads for eg request context info for logging or passing security context etc
Lot of plumbing code is required in java to do such simple things. Java8 added lamdba support and that has answer for such problems.
Using Lambda behavior can be passed as argument to any function and it is very powerful thing if you want to solve above problems.
Wrap Around
Template of wrap around function is something like below
Pre Code
Actual behavior
Post Code
WrapAround for loop
Above code is very straight forward , it has 2 functional interface one for condition & another one for block of code to execute and those 2 behavior is passed to loop function using lambda.
This allows us to introduce new construct
Lets look at some more example
WrapAround for time/stopwatch
WrapAround Closable/Exception
Java 8 has tons of feature that can make code concise and i used just one the the feature implement really useful thing.
Code used in blog is available @ github
- Loop construct for e.g do while/while/for loop
- Stopwatch around some code.
- Wrap checked exception with run time exception
- Initialization and cleanup for eg Threadpool creation/destruction or file open/close etc
- Adding context info to threads for eg request context info for logging or passing security context etc
Lot of plumbing code is required in java to do such simple things. Java8 added lamdba support and that has answer for such problems.
Using Lambda behavior can be passed as argument to any function and it is very powerful thing if you want to solve above problems.
Wrap Around
Template of wrap around function is something like below
Pre Code
Actual behavior
Post Code
WrapAround for loop
Above code is very straight forward , it has 2 functional interface one for condition & another one for block of code to execute and those 2 behavior is passed to loop function using lambda.
This allows us to introduce new construct
Lets look at some more example
WrapAround for time/stopwatch
WrapAround Closable/Exception
Java 8 has tons of feature that can make code concise and i used just one the the feature implement really useful thing.
Code used in blog is available @ github
No comments:
Post a Comment