Notes: Design Patterns

Tags

, ,

Gang Of Four Book

http://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns

Creational

Abstract Factory- Families of Objects (Factory of factories)

 Abstract Factory Pattern

 

Factory Method Pattern: Delegate Object Creation to specific base classes

 Factory Method Pattern

 

 

Builder Pattern:  Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

Builder Pattern

Prototype: Has Clone method

Prototype Pattern

 

Behavioral

Chain Of Responsibility: Client has no direct reference to the object that ultimately fulfills it. For example Print Button.

Chain Of Responsibility

 

Adapter Pattern:

Adaptor Pattern

 

Command Pattern:

 Command Pattern

 

Bridge

 

Bridge Pattern


Mediator – Object Behavioral

 

Mediator Pattern

 

Proxy:

Proxy Pattern

 

 

Decorator:

Decorator Pattern

 

 Strategy: Different strategies for different Implementations

 Strategy Pattern

  

State: State Of an Object

 State Pattern

 

Observer: Subscribe, Observe state change, unsubscribe

Observer Pattern

 

Pattern Classification

Pattern Classification

Notes: Spring AOP: 2: Proxying Mechanisms

Tags

Ref: Spring documentation
If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied. If the target object does not implement any interfaces then a CGLIB proxy will be created.

If you want to force the use of CGLIB proxying (for example, to proxy every method defined for the target object, not just those implemented by its interfaces) you can do so. However, there are some issues to consider:

○ final methods cannot be advised, as they cannot be overriden.
○ You will need the CGLIB 2 binaries on your classpath, whereas dynamic proxies are available with the JDK.
○ The constructor of your proxied object will be called twice. This is a natural consequence of the CGLIB proxy model whereby a subclass is generated for each proxied object. For each proxied instance, two objects are created: the actual proxied object and an instance of the subclass that implements the advice. This behavior is not exhibited when using JDK proxies. Usually, calling the constructor of the proxied type twice, is not an issue, as there are usually only assignments taking place and no real logic is implemented in the constructor.

To force the use of CGLIB proxies set the value of the proxy-target-class attribute of the element to true:


	<aop:config proxy-target-class="true">
		    <!-- other beans defined here... -->
	</aop:config>

To force CGLIB proxying when using the @AspectJ autoproxy support, set the ‘proxy-target-class’ attribute of the element to true:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Notes: Spring AOP: 2: Advice

Tags

, ,

Ref: Spring documentation
Advice is associated with a pointcut expression, and runs before, after, or around method executions matched by the pointcut. The pointcut expression may be either a simple reference to a named pointcut, or a pointcut expression declared in place.

Before Advice
○ Before advice is declared in an aspect using the @Before annotation:

		import org.aspectj.lang.annotation.Aspect;
		import org.aspectj.lang.annotation.Before;
		
		@Aspect
		public class BeforeExample {
			@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
			public void doAccessCheck() {
				// ...
			}
			
			@Before("execution(* com.xyz.myapp.dao.*.*(..))")
			public void doAccessCheckWithInplacePointcut() {
			// ...
			}
		}

After-returning Advice

	○ @AfterReturning( pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
					returning="retVal")
	public void doAccessCheck(Object retVal) {
			// ...
	}

○ The name used in the returning attribute must correspond to the name of a parameter in the advice method.
○ When a method execution returns, the return value will be passed to the advice method as the corresponding argument value.
○ A returning clause also restricts matching to only those method executions that return a value of the specified type (Object in this case, which will match any return value).
○ Please note that it is not possible to return a totally different reference when using after-returning advice.

After throwing advice

	○  @AfterThrowing( pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
					throwing="ex")
	public void doRecoveryActions(DataAccessException ex) {
		// ...
	}

○ The name used in the throwing attribute must correspond to the name of a parameter in the advice method.
○ When a method execution exits by throwing an exception, the exception will be passed to the advice method as the corresponding argument value.
○ A throwing clause also restricts matching to only those method executions that throw an exception of the specified type (DataAccessException in this case).

After (finally) advice

 @After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
	public void doReleaseLock() {
		// ...
	}

Around advice

 @Around("com.xyz.myapp.SystemArchitecture.businessService()")
	public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
		// start stopwatch
		Object retVal = pjp.proceed();
		// stop stopwatch
		return retVal;
	}

○ Around advice is declared using the @Around annotation.
○ The first parameter of the advice method must be of type ProceedingJoinPoint.
○ Within the body of the advice, calling proceed() on the ProceedingJoinPoint causes the underlying method to execute.
○ The proceed method may also be called passing in an Object[] – the values in the array will be used as the arguments to the method execution when it proceeds.
○ The value returned by the around advice will be the return value seen by the caller of the method. A simple caching aspect for example could return a value from a cache if it has one, and invoke proceed() if it does not.
○ Note that proceed may be invoked once, many times, or not at all within the body of the around advice, all of these are quite legal.

****************
Advice parameters

Access to the current JoinPoint
○ Any advice method may declare as its first parameter, a parameter of type org.aspectj.lang.JoinPoint
○ For around advice ProceedingJoinPoint is mandatory as the first argument.
○ JoinPoint interface provides some methods like
§ getArgs()
§ getThis() returns the proxy object
§ getTarget()
§ getSignature()
§ toString() – prints a useful description of the method being advised

Passing parameters to advice


@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
public void validateAccount(Account account) {
	// ...
}

Another way

@Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
private void accountDataAccessOperation(Account account) {}

@Before("accountDataAccessOperation(account)")
public void validateAccount(Account account) {
	// ...
}

Define the @Auditable annotation:


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auditable {
	AuditCode value();
}

Advice that matches the execution of @Auditable methods:
@Before("com.xyz.lib.Pointcuts.anyPublicMethod() && @annotation(auditable)")
public void audit(Auditable auditable) {
	AuditCode code = auditable.value();
	// ...
}

Determining argument names
○ Parameter names in pointcut expressions should match those used in advice and pointcut method signatures.

Parameter names are not available through Java reflection.
So Spring AOP uses the following strategies to determine parameter names:

Notes: Spring AOP: 2: Pointcuts

Tags

, ,

Ref: Spring documentation
Declaring A Pointcut
○ Pointcuts are collection of join-points.
○ Spring AOP only supports method execution join points for Spring beans. So pointcuts match only the execution of methods on Spring beans.
○ A pointcut declaration has two parts:
§ a signature comprising a name and any parameters,
§ a pointcut expression that determines exactly which method executions we are interested in.
○ In the @AspectJ annotation-style of AOP,
§ the pointcut signature is provided by a regular method definition,
§ the pointcut expression is indicated using the @Pointcut annotation
§ the method serving as the pointcut signature must have a void return type.
§ defining a pointcut named ‘anyOldTransfer’ that will match the execution of any method named ‘transfer':

@Pointcut("execution(* transfer(..))")                 // the pointcut expression
			private void anyOldTransfer() {}            // the pointcut signature

Supported Pointcut Designators (PCDs) in Spring
execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP within – limits matching to join points
Within- limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP)
this - limits matching to join points where the bean reference (Spring AOP proxy) is an instance of the given type
target - limits matching to join points where the target object (application object being proxied) is an instance of the given type
args - limits matching to join points where the arguments are instances of the given types
@target – limits matching to join points where the class of the executing object has an annotation of the given type
@args - limits matching to join points where the runtime type of the actual arguments passed have annotations of the given type(s)
@within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP)
@annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation

Since Spring AOP supports joinpoints only as the execution of methods, all the above designators act as further filtering criteria in addition to the execution of methods.

Additionally Spring supports its own PCD called ‘bean‘.
○ This PCD allows you to limit the matching of join points to a particular named Spring bean, or to a set of named Spring beans (when using wildcards)
○ Since wildcard (*) is supported, if we have some naming conventions for your Spring beans we can quite easily write a ‘bean’ PCD expression to pick them out.
○ This PCD is instance based (not type based)

All above PCDs can be &&’ed, ||’ed, and ! (negated) too.

Combining Pointcuts

@Pointcut("execution(public * *(..))")                                                //Matched against any public method
private void anyPublicOperation() {}

@Pointcut("within(com.xyz.someapp.trading..*)")    //execution of any public method in trading package
private void inTrading() {}

@Pointcut("anyPublicOperation() && inTrading()")                         //Above two combined
private void tradingOperation() {}

○ It is a best practice to build more complex pointcut expressions out of smaller named components as shown above.
○ When referring to pointcuts by name, normal Java visibility rules apply (you can see private pointcuts in the same type, protected pointcuts in the hierarchy, public pointcuts anywhere and so on). Visibility does not affect pointcut matching.

Any given pointcut is matched against public methods only.

For protected/private methods or constructors, consider the use of Spring-driven native AspectJ weaving (load time weaving) instead of Spring’s proxy-based AOP framework.

A well written pointcut should try and include at least the two types -kinded (execution, get, set, call, handler, etc )and scoping (within, withincode, etc) – whilst the contextual designators (ex- target, @annotation) may be included if wishing to match based on join point context, or bind that context for use in the advice.

Supplying either just a kinded designator or just a contextual designator will work but could affect weaving performance (time and memory used) due to all the extra processing and analysis.

Scoping designators are very fast to match and their usage means AspectJ can very quickly dismiss groups of join points that should not be further processed – that is why a good pointcut should always include one if possible.
***************************************************

Pointcut examples
“SystemArchitecture” aspect
○ Recommended approach – Define an aspect that captures common pointcut expressions for this purpose.

	package com.xyz.someapp;
	import org.aspectj.lang.annotation.Aspect;
	import org.aspectj.lang.annotation.Pointcut;
	
	@Aspect
	public class SystemArchitecture {
		
		/**
		* A join point is in the web layer if the method is defined 
		*in a type in the com.xyz.someapp.web package or 
		*any sub-package  under that. */
		@Pointcut("within(com.xyz.someapp.web..*)")
		public void inWebLayer() {}
		
		@Pointcut("within(com.xyz.someapp.service..*)")
		public void inServiceLayer() {}
		
		@Pointcut("within(com.xyz.someapp.dao..*)")
		public void inDataAccessLayer() {}
		
		@Pointcut("execution(* com.xyz.someapp.service.*.*(..))")
		public void businessService() {}
	}
	

Notice that all the above pointcut methods are public and
so can be used anywhere.

A business service is the execution of any method defined on a service interface. This definition assumes that interfaces are placed in the “service” package, and that implementation types are in sub-packages.

If we group service interfaces by functional area (for example, in packages *com.xyz.someapp.abc.service and com.xyz.def.service) then the pointcut expression “execution(* com.xyz.someapp..service.*.*(..))” could be used instead.

Alternatively, you can write the expression using the ‘bean’ * PCD, like so “bean(*Service)”. (Useful when we name Spring service beans in a consistent fashion.)

The most often used PCD is execution. The format of expression is
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

The elements ret-type-pattern, name-pattern, param-pattern are mandatory.
○ We can use * on ret-type pattern and name-pattern
○ For param-pattern
§ () matches methods which take no arguments.
§ (..) indicates any number of parameters
§ (*) one or more arguments
§ (*, String) two arguments – first of any type, second of String type.

Some examples
○ any join point where the target object implements the AccountService interface:
§ target(com.xyz.service.AccountService)
○ any join point which takes a single parameter, and where the argument passed at runtime is Serializable
§ args(java.io.Serializable)
§ Note that the pointcut given above is different to execution(* *(java.io.Serializable)): the args version matches if the argument passed at runtime is Serializable, the execution version matches if the method signature declares a single parameter of type Serializable.

Notes: Spring: AOP: 1

Tags

, ,

Ref: Spring documentation
Spring framework supports AspectJ annotations
○ No dependency on AspectJ compiler or weaver. However, their use enables us to use full support of AspectJ. What do I mean by full support?

Enabling AspectJ support
○ The @AspectJ support is enabled by including the following element inside your spring configuration:
§
§ Which schema is needed for this?
○ Also include two AspectJ jars:
§ aspectjrt.jar
§ aspectjweaver.jar

Declaring and Aspect
○ Declare the bean in XML
○ Annotate the class with @Aspect

Notes:
○ Aspects (classes annotated with @Aspect) may have methods and fields just like any other class. They may also contain pointcut, advice, and introduction (inter-type) declarations.
○ @Aspects are excluded from auto-proxying. So in Spring we cannot advise aspect themselves with other aspects.

Quick Notes: WSDL

Tags

,

WSDL is a document written in XML. The document describes a Web service. It specifies the location of the service and the operations (or methods) the service exposes.

WSDL main elements:

Element Defines
The data types used by the web service
The messages used by the web service
The operations performed by the web service
The communication protocols used by the web service

WSDL Example

<message name="getTermRequest">
  <part name="term" type="xs:string"/>
</message>

<message name="getTermResponse">
  <part name="value" type="xs:string"/>
</message>

<portType name="glossaryTerms">
  <operation name="getTerm">
    <input message="getTermRequest"/>
    <output message="getTermResponse"/>
  </operation>
</portType>

WSDL Binding With SOAP

<message name="getTermRequest">
  <part name="term" type="xs:string"/>
</message>

<message name="getTermResponse">
  <part name="value" type="xs:string"/>
</message>

<portType name="glossaryTerms">
  <operation name="getTerm">
    <input message="getTermRequest"/>
    <output message="getTermResponse"/>
  </operation>
</portType>

<binding type="glossaryTerms" name="b1">
   <soap:binding style="document or rpc"
   transport="http://schemas.xmlsoap.org/soap/http" />
   <operation>
     <soap:operation soapAction="http://example.com/getTerm"/>
	     <input><soap:body use="literal"/></input>
	     <output><soap:body use="literal"/></output>
  </operation>
</binding>

Quick Notes: SOAP

Tags

,

SOAP is a simple XML-based protocol to let applications exchange information over HTTP.
# SOAP is a protocol for accessing a Web Service.
# SOAP stands for Simple Object Access Protocol
# SOAP is a communication protocol
# SOAP is for communication between applications
# SOAP is a format for sending messages

A SOAP message is an ordinary XML document containing the following elements:
* An Envelope element -identifies the XML document as a SOAP message
* A Header element that contains header information
* A Body element that contains call and response information
* A Fault element containing errors and status information

A SOAP HHTP Web Service Request:

POST /item HTTP/1.1
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 250

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body>
	  <m:GetPrice xmlns:m="http://www.w3schools.com/prices">
		    <m:Item>Apples</m:Item>
	  </m:GetPrice>
</soap:Body>
</soap:Envelope>

A SOAP Response

<soap:Body>
	  <m:GetPriceResponse xmlns:m="http://URL/prices">
		    <m:Price>1.90</m:Price>
	  </m:GetPriceResponse>
</soap:Body>
</soap:Envelope>

SOAP Fault Element
If a Fault element is present, it must appear as a child element of the Body element.
A Fault element can only appear once in a SOAP message.

Sub Element Description
A code for identifying the fault
A human readable explanation of the fault
Information about who caused the fault to happen
Holds application specific error information related to the Body element

Error Description
VersionMismatch Found an invalid namespace for the SOAP Envelope element
MustUnderstand An immediate child element of the Header element, with the
mustUnderstand attribute set to “1”, was not understood
Client The message was incorrectly formed or contained incorrect information
Server There was a problem with the server so the message could not proceed

Follow

Get every new post delivered to your Inbox.