Simple examples of several common design patterns in Java

Source: Internet
Author: User

1. Single Case design mode

The so-called single-case design mode is simply said that no matter how the program runs, a single-instance design pattern of the class (Singleton Class) will always have only one instantiation of the object generated. The specific implementation steps are as follows:

(1) The construction method of a class with a singleton design pattern is privatized (with private modification).

(2) The instantiation object of the class is generated within it and encapsulated as a private static type.

(3) Defines a static method that returns an instance of the class.

The sample code is as follows:

class Singleton {private static Singleton instance = new Singleton ();//Internally generated this       The instantiated object of the class public static Singleton getinstance () {//Returns the instance object return instance through a static method; } private Singleton () {//encapsulates the construction method as privatized} public void print () {System.out.println ("Hello Wo     Rld!!! ");}}          public class Singletondemo {public static void main (String args[]) {Singleton S1 = null;//Declaration Object Singleton s2 = null; Declares the object Singleton s3 = null; Declaring object S1 = Singleton.getinstance (); Gets the instantiated object s2 = singleton.getinstance (); Gets the instantiated object s3 = Singleton.getinstance (); Gets the instantiated object S1.print (); Call Method S2.print (); Call Method S3.print (); Call Method}} 

Introduction of a single-case model
Singleton is a pattern of creation in which a class takes Singleton mode, and when the class is created, it is possible to generate only one instance for external access and provide a global access point

Second, the realization of the singleton pattern

There are four ways to achieve this:

/**   *    * Single-instance mode implementation: A Hungry man, thread-safe but less efficient * * Public  class Singletontest {         private singletontest () {       }         private static Final Singletontest instance = new Singletontest ();         public static Singletontest getinstancei () {           return instance;       }     }  

  

/**   * Singleton mode implementation: Full-Chinese, non-thread-safe    *    *  /public class Singletontest {       private singletontest () {       }         private static singletontest instance;         public static Singletontest getinstance () {           if (instance = = null)               instance = new Singletontest ();           return instance;       }   }  

  

/**   * thread safe, but very inefficient   * @author vanceinfo * */Public  class Singletontest {       private Singletontest () {       }         private static singletontest instance;         public static synchronized Singletontest getinstance () {           if (instance = = null)               instance = new Singletontest (); 
   return instance;       }   }  

  

/**   * thread safe  and high efficiency * */public  class Singletontest {       private static singletontest instance;         Private Singletontest () {       } public         static Singletontest getistance () {           if (instance = = null) {               Synchronized (singletontest.class) {                   if (instance = = null) {                       instance = new Singletontest ();}               }           }           return instance;       }   }  

  

2. Factory design mode

The program adds a transition between the interface and the subclass, through which the sub-class instantiation object that implements the common interface can be dynamically obtained.

The sample code is as follows:

Interface Animal {//define an animal interface public void say ();//Speech Method} class Cat implements Animal {//define subclass Cat @Over Ride public void Say () {//Overwrite say () method System.out.println ("I'm a cat, Meow!       "); }} class Dog implements Animal {//define subclass dog @Override public void Say () {//Overwrite say () method System. Out.println ("I'm a puppy, bark!       ");  }} class Factory {//define factory class public static Animal getinstance (String className) {Animal a = null;//           Define the interface object if ("Cat". Equals (ClassName)) {//Determine which subclass is the tag a = new Cat ();//Instantiate the interface through the Cat subclass} if ("Dog". Equals (ClassName)) {//Determine which child class is the token of a = new Dog ();//Instantiate interface through the Dog subclass} return       A           }} public class Factorydemo {public static void main (string[] args) {Animal a = null;//define Interface object A = Factory.getinstance (Args[0]);   Gets the instance through the factory if (a = null) {//Determines whether the object is empty A.say ();//Call Method}    }} [Java] View plain  

  

3. Proxy design mode

Refers to an agent theme that operates on real topics, real-world topics that perform specific business operations, and agent topics that are responsible for other related business processes. For example, in life through the proxy access network, the customer through the Network proxy Connection network (specific business), the proxy server to complete user rights and access restrictions and other Internet-related operations (related business).

The sample code is as follows:

Interface Network {//define network interface public      void browse ();//define the abstract method of browsing  }     class Real implements Network {//Real Internet operation public      void browse () {//Overwrite abstract method          System.out.println ("Internet browsing information! ");       }   }     Class Proxy implements network {//proxy Internet      private network network;         Public Proxy (Network network) {//Set the real operation of the agent          this.network = Network;//Set the subclass of the proxy      } public         void Check () {//Body Verification Action          System.out.println ("Check if the user is legal! ");       }         public void browse () {           this.check ();//Invoke specific proxy business Operation          This.network.browse ();//Invoke Real Internet Operation      }   }     public class Proxydemo {public       static void Main (String args[]) {           Network net = null;//define Interface object          net = new P Roxy (New Real ()); Instantiate the proxy while the actual operation of the incoming agent          net.browse ();//Invoke Agent's Internet Operation       }   }  

  

Simple examples of several common design patterns in Java

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.