OO design recommendations for J2EE applications (2)

Source: Internet
Author: User
The template method design pattern

Template Method

One good use of concrete inheritance is to implementTemplate MethodDesign pattern.

A good usage of class inheritance is to implement the template method design mode.

the template method design pattern (gof) addresses a common problem: We know the steps of an algorithm and the order in which they shoshould be placed med, but don't know how to perform all of the steps. this template method pattern solution is to encapsulate the individual steps we don't know how to perform as abstract methods, and provide an abstract superclass that invokes them in the correct order. concrete subclasses of this abstract superclass implement the abstract methods that perform the individual steps. the key concept is that it is the abstract base class that controls the workflow. public superclass methods are usually final: The Abstract METHODS deferred to subclasses are protected. this helps to reduce the likelihood of bugs: All subclasses are required to do, is fulfill a clear contract.

The template method design model (gof) emphasizes a common problem: we know thatAlgorithmBut we do not know how to execute all these steps. The template method mode is used to solve the problem of using steps we do not know how to execute as an abstract method, and provide an abstract parent class to call them in the correct order. Abstract The specific subclass of the parent class to implement this specific method. The key point is that abstract classes control the process. The common parent class method is usually final: the abstract method is extended to the subclass of protected. This helps reduce the number of bugs possible: All subclasses are required to do so, meeting a clear responsibility.

The centralization of workflow logic into the abstract superclass is an exampleInversion of Control. Unlike in traditional class libraries, where user code invokes library code, in this approach framework code in the superclass invokes user code. It's also known asHollywood principle:"Don't call me, I'll call you". inversion of control is fundamentalFrameworks,Which tend to use the template method pattern heavily (we'll discuss frameworks later ).

An example of control inversion is to centralize the workflow logic into an abstract class. Unlike traditional class librariesCodeCall the class library and use this method to call the user code in the Framework Code of the super class. It is a well-known Hollywood principle: "Don't call me, I will call you ". Inversion of control is the basis of the Framework, which makes the template method model more cumbersome.

For example, consider a simple order processing system. the business involves calculating the purchase price, based on the price of individual items, checking whether the customer is allowed to spend this amount, and applying any discount if necessary. some persistent storage such as an RDBMS must be updated to reflect a successful purchase, and queried to obtain price information. however, it's desirable to separate this from the steps of the business logic.

For example, consider a simple order processing system. This business involves calculating the purchase price. Based on the price of each item, check whether the customer is allowed to spend this amount, and if necessary, discount.

Some persistent storage, such as RDBMS, must update a successful purchase record to the database and query for price information. However, it is expected to separate these steps from the business logic.

TheAbstractorderejbSuperclass implements the business logic, which implements des checking that the customer isn't trying to exceed their spending limit, and applying a discount to large orders. The publicPlaceorder ()Method is final, so that this workflow can't be modified (or already upted) by subclasses:

The abstractorderejb parent class implements the business logic, including checking whether the customer has exceeded their purchase limit and applying a discount to a large order. The common placeorder () method is final, so that the workflow can be modified by the quilt class.

 Public   Final Invoice placeorder ( Int Customerid, invoiceitem [] items)
Throws Nosuchcustomerexception, spendinglimitviolation {

Int Total = 0;
For ( Int I = 0; I <items. length; I ++ ){
Total + = getitemprice (items [I]) * items [I]. getquantity ();
}

If (Total> getspendinglimit (customerid )){
Getsessioncontext (). setrollbackonly ();
Throw New Spendinglimitviolation (total, limit );
}
Else If (Total> discount_threshold ){
// Apply discount to total...
}

Int Invoiceid = placeorder (customerid, total, items );
Return New Invoiceimpl (IID, total );
}

I 've highlighted the three lines of code in this method that invoke protected abstract "template methods" that must be implemented by subclasses. These will be defined inAbstractorderejbAs follows:

I highlighted three lines of code in this method. They call the protected Abstract "template method", which must be implemented by the quilt class and are defined in javasactoderejb:

 Protected   Abstract   Int Getitemprice (invoiceitem item );

Protected Abstract Int Getspendinglimit (customerid)
Throws Nosuchcustomerexception;

Protected Abstract Int Placeorder ( Int Customerid, Int Total,
Invoiceitem [] items );

SubclassesAbstractorderejbMerely need to implement these three methods. they don't need to concern themselves with business logic. for example, one subclass might implement these three methods using JDBC, while another might implement them using sqlj or JDO.

The subclass of abstarctorderejb only needs to implement these three methods. They do not need to consider their own business logic. For example, a subclass may implement these three methods using JDBC, but other implementations may use sqlj or JDO.

Such uses of the template method pattern offer good separation of concerns. here, the superclass concentrates on business logic; the subclasses concentrate on implementing primitive operations (for example, using a low-level API such as JDBC ). as the template methods are protected, rather than public, callers are spared the details of the class's implementation.

This usage of the template method mode provides a good separation of concerns. In this way, the parent class only needs to be centralized with the business logic; the Child class focuses on implementing basic operations (for example, using a low-level API like JDBC ). Since the template method mode is protected, rather than the public method, the caller is separated from the class implementation details.

As it's usually better to define types in interfaces rather than classes, the template method pattern is often used as a strategy to implement an interface.

Since defining interfaces is better than defining classes, the template method mode is usually used to implement interface policies.

Note

Note:

Abstract superclasses are also often used to implement some, but not all, methods of an interface. the remaining methods-which vary between concrete implementations-are left unimplemented. this differs from the template method pattern in that the abstract superclass doesn' t handle workflow.

Abstract classes are also used to implement some interface methods. The remaining methods-changed in actual implementations-are left unimplemented. The template method mode differs from the abstract class in the processing workflow.

Important

Important

Use the template method design pattern to capture an algorithm in an abstract superclass, but defer the implementation of individual steps to subclasses. this has the potential to head off bugs, by getting tricky operations right once and simplifying user code. when implementing the template method pattern, the abstract superclass must factor out those methods that may change between subclasses and ensure that the method signatures enable sufficient flexibility in implementation.

In the abstract class, a series of algorithms are defined in the template mode, but different steps are postponed to the subclass. This potentially hinders bugs and captures complicated operations to simplify user code. When implementing the template method mode, abstract the parent class must extract the methods that may be changed in the subclass and ensure that the method signature has sufficient flexibility in implementation.

Always make the abstract parent class implement an interface. The template method design pattern is especially valuable in Framework Design (discussed towards the end of this chapter ).

The abstract parent class always implements an interface. The template method design pattern has special value in the Framework Design (discussed at the end of this chapter ).

The template method design pattern can be very useful in J2EE applications to help us to achieve as much portability as possible between application servers and databases while still leveraging proprietary features. we 've seen how we can sometimes separate business logic from database operations above. we cocould equally use this pattern to enable efficient support for specific databases. for example, we cocould haveOracleorderejbAndDb2orderejbThat implemented the abstract template methods efficiently in the respective databases, while business logic remains free of proprietary code.

The template method pattern is very helpful in J2EE applications to help us achieve more portability between the application server and the database, while maintaining proprietary features. We have seen that we sometimes separate the business logic from the database. We can use this mode to effectively support specific databases. For example, oracleorderejb and db2orderejb effectively implement the abstract template method in their respective data, although the business logic is still free of charge for all the code.

The Strategy Design Pattern

Rule Mode

An alternative to the template method isStrategyDesign pattern, which factors the variant behavior into an interface. thus, the class that knows the algorithm is not an abstract base class, but a concrete class that uses a helper that implements an interface defining the individual steps. the strategy design pattern takes a little more work to implement than the template method pattern, but it is more flexible. the advantage of the Strategy pattern is that it need not involve concrete inheritance. the class that implements the individual steps is not forced to inherit from an abstract template superclass.

Another choice of the template method mode is the policy mode, which extracts variable behaviors into an interface. Therefore, an algorithm class is not an abstract class, but a class that defines the specific operation steps and implements the interface with the help class. The policy design mode is more flexible than the template method mode. The advantage of policy mode is that it does not need to call a specific class. The specific operation steps of the implementation class are not forced to inherit from an abstract template class.

Let's look at how we cocould use the strategy design pattern in the above example. The first step is to move the template methods into an interface, which will look like this:

Let's see how we use the policy pattern in the following example. The first step is to move the template method to an interface, which looks like this:

Public InterfaceDatahelper {
IntGetitemprice (invoiceitem item );
IntGetspendinglimit (customerid)ThrowsNosuchcustomerexception;
IntPlaceorder (IntCustomerid,IntTotal, invoiceitem [] items );
}

Implementations of this interface don't need to subclass any special class; we have the maximum possible freedom.

No specific subclass is required to implement this interface; we have the maximum freedom.

Now we can write a concreteOrderejbClass that depends on an instance variable of this interface. we must also provide a means of setting this helper, either in the constructor or through a bean property. in the present example I 've opted for a bean property:

Now I am writing a specific orderejb instance variable that relies on this interface. We must provide a way to set this helper class, or in the constructor or through a bean attribute. In the current example, I select the bean attribute.

PrivateDatahelper;

Public VoidSetdatahelper (datahelper newdatahelper ){
This. Datahelper = newdatahelper;
}

The implementation ofPlaceorder ()Method is almost identical to the version using the template method pattern, doesn't that it invokes the operations it doesn't know how to do on the instance of the Helper interface, In the highlighted lines:

The implementation of the placeorder () method is almost the same as that of the template method. Except for the operation called by the placeorder () method, it does not know how to instantiate the Helper interface. In the highlighted line:

 Public   Final Invoice placeorder ( Int Customerid, invoiceitem [] items)
Throws Nosuchcustomerexception, spendinglimitviolation {

Int Total = 0;
For ( Int I = 0; I <items. length; I ++ ){

Total + = This . Datahelper. getitemprice (items [I]) *
Items [I]. getquantity ();
}

If (Total> This . Datahelper. getspendinglimit (customerid )){
Getsessioncontext (). setrollbackonly ();
Throw New Spendinglimitviolation (total, limit );
} Else If (Total> discount_threshold ){
// Apply discount to total...
}

Int Invoiceid = This . Datahelper. placeorder (customerid, total, items );
Return New Invoiceimpl (IID, total );
}

This is slightly more complex to implement than the version using concrete inheritance with the template method pattern, but is more flexible. this is a classic example of the tradeoff between concrete inheritance and delegation to an interface.

This is a little more complicated to implement than using the template method mode in the inherited version of the class, but it is also more flexible. This classic conversion example inherits classes and delegates them to an interface.

I use the strategy pattern in preference to the template method pattern under the following circumstances:

In the following cases, the policy mode is better than the template method mode:

  • When all steps vary (rather than just a few ).

  • When all steps are different (compared to only a little bit)

  • When the class that implements the steps needs an independent inheritance hierarchy.

  • When the class implementation step requires a dependency inheritance level.

  • When the implementation of the steps may be relevant to other classes (this is often the case with J2EE data access ).

  • When the implementation of the step may be associated with other classes (this is often sent during J2EE data access ).

  • When the implementation of the steps may need to vary at run time. Concrete inheritance can't accommodate this; delegation can.

  • This implementation step needs to change at runtime. Class inheritance cannot adapt to this, and proxy can.

  • When there are unsupported different implementations of the steps, or when it's expected that the number of implementations will continue to increase. in this case, the greater flexibility of the Strategy pattern will almost certainly prove beneficial, as it allows maximum freedom to the implementations.

  • There are many different implementation steps here, or when it expects that the number of implementations will continue to grow. In this case, the great flexibility of this policy model will almost certainly provide benefits, as it allows for the maximization of freedom.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.