Simple examples of several common design patterns in Java

Source: Internet
Author: User

1. Single Case design pattern

The so-called single case design pattern is simply that no matter how the program is run, a singleton design pattern class (Singleton Class) will always have only one instantiation object generated. The following steps are implemented:

(1) Privatization of classes constructed using a single example design pattern (with private modification).

(2) Creates an instantiated object of the class within it and encapsulates it as a private static type.

(3) Define a static method to return an instance of the class.

The sample code is as follows:

  Java code   class singleton {       private static  Singleton instance = new singleton ();//  internally generates an instantiated object of this class            public static singleton getinstance ()  { //  return instance object via static method            return instance;       &nbsp           private singleton ()  { //  encapsulates the construction method as privatization        }            public void print ()  {            SYSTEM.OUT.PRINTLN ("Hello world!!!");       &nbsp}   }       Public class singletondemo  {       public static void main (string Args[])  {           Singleton s1 = null;  //  declaring Objects            Singleton s2 =  null; //  Declaration Object            singleton s3 =  null; //  declaring Objects            s1 =  Singleton.getinstance (); //  get instantiated objects            S2  = singleton.getinstance (); //  to obtain the instantiated object             s3 = singleton.getinstance (); //  to obtain the instantiated object             s1.print (); //  call method             s2.print (); //  call method            s3.print ();  //  Calling Method  &nbsp    &NBSP}   }  

class Singleton {private static Singleton instance = new Singleton ();
	The instantiated object of this class is public static Singleton getinstance () {//Returns the instance object return instance by static method;
	Private Singleton () {//To encapsulate the construction method as privatized} public void print () {System.out.println ("Hello world!!!"); } public class Singletondemo {public static void main (String args[]) {Singleton S1 = null;//declaring Object Singleton s2 = NULL; Declares the object Singleton s3 = null; Declaration Object S1 = singleton.getinstance (); Obtain the instantiated object s2 = singleton.getinstance (); Obtain the instantiated object S3 = Singleton.getinstance (); Obtain the instantiated object S1.print (); Call Method S2.print (); Call Method S3.print (); Call Method}} 

  One, Introduction to Singleton mode
     Singleton is a type of creation pattern that refers to a class that uses the singleton mode, and after that class is created, only one instance can be generated for external access. and provides a global access point

Two, the implementation of the single example mode

implementation of the following four kinds:
Java code  /**    *     *  single case 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;        &NBSP}      }  

/** * * Single case Mode implementation: A Hungry man, thread-safe but less efficient * * public class Singletontest {private Singleto

	Ntest () {} private static final singletontest instance = new Singletontest ();
	public static Singletontest Getinstancei () {return instance; }

}


Java code  /**    *  Single example 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;        }   }  

/** * Single case 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; }
}


Java code  /**    *  thread safety, but very inefficient    *  @author  vanceinfo    * & nbsp  */   public class singletontest {       private  singletontest ()  {                   private static SingletonTest instance;           public static synchronized 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
	}
}


Java code  /**    *  thread safety    and high efficiency    *    */   public  class singletontest {       private static singletontest  instance;           private singletontest ()  {       &NBSP}           public static SingletonTest  Getistance ()  {           if  (instance ==  NULL)  {               synchronized   (singletontest.class)  {                    if  (instance == null)  {                        Instance = new singletontest ();                    }                }             }            return  Instance        }   }  

2. Factory design mode

The program joins a transition end between the interface and the subclass, through which the subclass instantiation object that implements the common interface can be obtained dynamically.

The       sample code is as follows: Java code   interface animal { //  defines an animal interface         public void say (); //  speaking method   }        class cat implements animal { //  define subclass cat         @Override        public void say ()  { //  Say () method            system.out.println ("I'm a cat, Meow.") ");       &nbsp}   }       class dog implements  animal { //  definition Subclass dog           @Override         public void say ()  { //  overwrite Say () method             system.out.println ("I'm a puppy, barking.") ");       &nbsp}   }       class factory { //  define factory class        public static  Animal getinstance (string classname)  {            Animal a = null; //  define interface Objects             if  ("Cat". Equals (ClassName))  { //  determine which subclass of the tag                 a = new cat (); //  instantiate interface via Cat subclass            }             if  ("Dog". Equals (ClassName))  { //  determine which subclass of the tag                 a = new dog (); //  interface by Dog subclass            }             return a;       &nbsp}   }       Public class factorydemo  {          public static void main (string[]  args)  {           animal a = null; / /  defines interface objects            a = factory.getinstance ( Args[0]; //  through the factory to obtain the instance            if  (a !=  null)  { //  Determine if the object is empty                 a.say (); //  invoke method            }        }   }  

Interface Animal {//define an animal interface public
	void Say ()//Speak Method
}

class Cat implements Animal {//define subclass Cat
	@Ove Rride 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 am small Dog, Barking. ");
	}
}

Class Factory {//define factory class public
	static Animal getinstance (String className) {
		Animal a = null;//define Interface object
		if ("Cat". Equals (ClassName)) {//judge which subclass of tag
			a = new Cat ()//instantiate interface through Cat subclass
		}
		if ("Dog". Equals (ClassName)) {//determine which subclass of the tag
			a = new Dog (); Instantiate interface via dog subclass} return
		A;
	}

public class Factorydemo {public

	static void Main (string[] args) {
		Animal a = null;//define Interface object
		a = Factory. GetInstance (Args[0]); Get the instance through
		the factory if (a!= null) {//Determine if the object is empty
			A.say ();//Call Method
		}
}}

3. Agent design mode

       means to operate a real subject by an agent theme, to perform specific business operations on the real subject, and to handle other related business with the agent subject. For example, in life through the proxy access network, the customer through the Network Agent Connection network (specific business), by the proxy server to complete user rights and access restrictions and other Internet related operations (related business).

      sample code is as follows: Java code   interface network { //  definition Network interface         public void browse (); //  Define the browsing abstract method   }       class real implements network { //  Real-World Internet operation         public void browse ()  { //  override abstract methods             SYSTEM.OUT.PRINTLN ("Browsing information on the internet.") ");       &nbsp}   }       class proxy implements  Network { //  Agent Internet        private Network network;           public proxy (network network)  {//  Set the real operation of the agent            this.network = network; //   Set up the surrogate subclass        }           public void check ()  { //  Authentication Operations             system.out.println ("Check if the user is legitimate.) ");        }           

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.