Easy to master Java template patterns _java

Source: Internet
Author: User

definition: An abstract class exposes the way/template that defines the method that executes it. Its subclasses can override the method implementation as needed, but the invocation will be done in a way defined in the abstract class

Characteristics:

1, the package invariant part, expands the variable part.

2, the extraction of public code, easy to maintain.

3, the behavior is controlled by the parent class, the subclass realizes.

Enterprise-class development and applications in common frameworks: the implementation of Hibernate in spring (open transactions, open sessions, close session)

Example : the following to play the game for example, all games have two operations to play, open the game and close the game, but play in the middle of the way is not the same, see the actual example below.

public class Demo {public
 static void Main (string[] args) {
 Game g1 = new LOL ();
 Game g2 = new CF ();
 G1.playgame ();
 G2.playgame ();
 }

Abstract class game{
 protected void init () {
 System.out.println ("Initializing the game and landing the game ...)". ");
 }
 public abstract void Play ();
 protected void End () {
 System.out.println ("ending the game and exiting the login ...) ");
 }
 public void PlayGame () {
 init ();
 Play ();
 End ();
 }

Class LOL extends game{public
 void Play () {
 System.out.println ("Playing the Hero League game")
 ;
}

Class CF extends game{public
 Void plays () {
 System.out.println ("Play more FireWire");
 }


Template pattern is actually the application of abstract class, this model is relatively simple, and in actual development also use more.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.