Πέμπτη 27 Ιανουαρίου 2022

Flyweight pattern

  • What problem does Flyweight pattern solve?



Suppose we need to create and log Vehicle objects with random locations, at regular intervals, for an extended period

If we just create "new Vehicle().." every time, we will definitely get and OutOfMemory exception



How are we going to approach this issue?

Consider that we only need new locations. The Vehicle object instantiation is the same every time.



  • How does Flyweight pattern solve this?


We use the Factory pattern to provide the same Vehicle object to the caller, and then we can just set the random locations, and log it

Thus, our memory will now handle only 2 objects (one Truck and one Car)


This VehicleFactory has a vehicles property that holds only one instance of each vehicle type


Finally we use this factory to replace our previous "new Car()..", "new Truck()..", and set location, and log





Facade pattern

  • What problem does Facade pattern solve?



Suppose a caller client needs to make a vacation booking through a vacation company, including:

- Flight
- Hotel
- Car rental 

The client should only need to send his dates to the company.

He must do himself the flight, car and hotel bookings, one-by-one.

So below code should be fixed:


  • How does Facade pattern solve this?



We simply create a VacationFacade class, that includes all actions required to book a holiday (flight, hotel and car)




And finally use it in our client part















Τετάρτη 26 Ιανουαρίου 2022

Decorator pattern

  • What problem does Decorator pattern solve?



Suppose we have a hierarchy of shape objects:





At some point we may need a Circle with a red border layout dynamically.

Is it correct to create another concrete class statically?




No, we would duplicate our code, for only one little adjustment of a red border.

In addition, we can't have an extra interface for our new requirement, because all Components will have to implement the red border.

We also want a dynamic change only. 




  • How does Decorator pattern solve this?



The decorator pattern allows you to alter behavior dynamically, without affecting other objects of the same type.


We create an extra concrete class that 
- implements Component
- takes our to-be-decorated object as a constructor argument
- has generic functionality (add red border) for all Component objects
- has sole responsibility to add a red border





Code:


Use:

Only circle2 with have a red border


Note that ComponentWithRedBorder delegates execution to the original Component object, after having decorated it.






 



Τρίτη 25 Ιανουαρίου 2022

Composite pattern

  • What problem does Composite pattern solve?



Suppose we have some classes, like:
- Manager
- SalesPerson

that have similar functionality of payExpenses()

How are we going to execute payExpenses() for all Managers and all SalesPersons?

Do we really need to call payExpenses() for each type of these 2 entities, like:
- manager.payExpenses()
- salesPerson.payExpenses()
?

No.
We could have only one payExpenses() to handle all these cases,
in order to
-  reduce code duplication 
-  improve code readability 
-  improve code extendability


  • How does Composite pattern solve this?


- We will just have one Payee interface's payExpenses() method to handle all cases
- All related entities will implement the same Payee interface


1. Create a Payee interface with one payExpenses() method




2. Manager and SalesPersons will implement the same Payee interface

For example, Manager:

    public class Manager implements Payee {

      public void payExpenses(int amount) {
        // pay manager procedure...
      }

   }


3. Lets' replace manager and salesPerson references with the new Payee interface type

Before:


After:


4. Finally, in our Main method we use the new structure, like:

Suppose jane is a Manager, bob and sue are SalesPerson-s







Bridge Pattern

  • What problem does Bridge pattern solve?



Suppose we have a red Triangle, a red Square, and a red Circle shape

What if we want a yellow, green, purple etc. for each of above shapes?
Will we create a new class, like YellowCircleShape, PurpleCircleShape, etc.,  for each case?

This will lead to overpopulation of objects in a huge hierarchy, not manageable at all.

This may seem ok:


But not this one:







  • How does Bridge pattern solve this?


-Decouple Shapes and Colors
-Create a Color once, and re-use it in any Shape

1. Distinguish Shapes and Colors hierarchies



2. Color classes will have the sole responsibility of altering the color of the underlying Shape reference (using Graphics reference)



3. Shape classes will accept Colors in their constructors (Bridge)



4. Use final Shape classes, passing the Color as parameter:























Adapter pattern

  • What problem does Adapter pattern solve?



Suppose we have a common PriceCalculator interface for:

- CarPriceCalculator 
- TruckPriceCalculator 

in order to call printVehiclePrice() for both of them:




At some point, we may want to add an extra UKPriceCalculator, that doesn't/shouldn't belong (e.g. a third party calculator) to above hierarchy, and thus cannot implement PriceCalculator, and cannot call printVehiclePrice()




  • How does Adapter pattern solve this?


1. Create an Adapter class implementing PriceCalculator interface
2. Add a UKCarPriceCalculator class property


3. Override PriceCalculator's calculatePrice(), referring UKCarPriceCalculator methods


4. Finally, use the new Adapter class in main method









Παρασκευή 5 Νοεμβρίου 2021

Spring Certification: Aspect-Oriented Programming (AOP)

What is the concept of AOP? Which problem does it solve? What is a cross cutting concern?

  • AOP is a programmatic technique to apply separation of concerns regarding cross-cutting concerns, like transaction management, security, logging and more. It allows to decouple these concerns from tangling with the business code. Thus, reduces duplicating same code. It uses "advices" applied on "pointcuts" upon calling.
  • Cross-cutting corcerns are basic functionalities that complement the business code, like the mentioned above.


What is a pointcut, a join point, an advice, an aspect, weaving?

  • Pointcut: predicate that matches join points with advice
  • Join Point: represents the effective execution of a method where the aspect applies
  • Advice: the action taken by Aspect at a join point
  • Aspect: modularization of a concern that cuts across multiple classes
  • Weaving: program transformation that applies the aspect to the target object, in order to create the advised object (target object). Happens in runtime for Spring AOP, and in compile-time and runtime for AspectJ.



How does Spring solve (implement) a cross cutting concern?

  • Spring makes use of  proxy objects that wrap the target bean and intercept any method invocations that are defined by the pointcuts of an advice. These proxies are created at runtime, and can be JDK Dynamic proxies (Spring default) or CGLIB proxies


Which are the limitations of the two proxy-types?
  • JDK Dynamic Proxy
    • Target class must implement an interface
    • Only public methods that reside in interface can be proxied
    • If target method is calling another method, proxy won't work for this second method
  • CGLIB proxy
    • Target class and methods must not be final
    • Protected and public visibilities are supported
    • No self-invocation as for JDK Dynamic proxy
    • Needs and extra library spring-core, while JDK Dynamic proxy is built-in


How many advice types does Spring support? Can you name each one?

  • Before advice
    Performs some action, and then proceeds to execution of JoinPoint
    If any exception occurs though, it does not proceed.



  • After (finally) advice
    Always executes after target method has run, regardless of exception or success.





  • After Returning advice
    Executes after successful completion of JoinPoint's target method
    Provides access to returned object with "returning" attribute



  • After Throwing advice
    Executes only if target method contains an exception
    Provides access to returned object with "throwing" attribute


  • Around advice
    The most useful advice, it can manipulate the target method's params, catch exceptions from it and advice itself, and handle normal execution result.
    It can catch any exception of target method execution inside it immediately



What do you have to do to enable the detection of the @Aspect annotation? What does @EnableAspectJAutoProxy do?
  • We would need to enable AspectJ support, thus add spring-aspects dependency in pom
  • Annotate a @Configuration file with @EnableAspectJAutoProxy
  • Finally, in our @Component that we'll apply advices and pointcuts, annotate it with @Aspect
    If we have @Bean for this, annotate Bean POJO class with @Aspect
  • @EnableAspectJAutoProxy annotation activates the support for components marked with AspectJ’s @Aspect annotation 


If shown pointcut expressions, would you understand them?
  • execution(public * com.code.in.packets.SomeBean.*(int, ..))
    Targets all methods of SomeBean of com.code.in.packets package, that return anything, are public and take one int and any other parameters
  • within(com.code.in.*)    
    Targets all methods of all classes in com.code.in package and all subpackages
  • within(SomeInterface+)
    Matches for all the methods of classes that implement the 
    SomeInterface
  • within(com.code.in.packets.SomeService+)
    Matches for SomeService class and for all of its subclasses


What is the JoinPoint argument used for?
  • Upon advice invocation, JoinPoint parameter holds reference to an object that holds static information about the join point. From a JoinPoint we can access:
  1. target object - getTarget()
  2. method signature - getSignature()
  3. method arguments - getArgs() methods.


What is a ProceedingJoinPoint? Which advice type is it used with?
  • ProceedingJoinPoint is a type JoinPoint, used on @Around advice.
  • It is the first parameter of the advice
  • It has a proceed() method used to call the join point, which also could alter the parameters of the target method

-----------------------------------------------------------------------------------------------------


Questions from EDU-1202 exam (2021)


What advice is used to stop the propagation of an exception up the call stack?
  • Around advice can catch any exception from the target method execution, and throw an other, or do something else. Because Around wraps the executed method, it has complete control over the flow.