Java-language generic programming implementation singleton mode

Source: Internet
Author: User

Today to interview, the interviewer asked a design mode---Singleton mode, which is our most commonly used design mode, because of limited interview time, I just how to use generic programming to implement a single-case mode roughly speaking. Now the main talk about how to use generic programming to implement a singleton mode, using a small amount of code, to achieve a one-time method.

Let's take a look at our simple object:

Package singleton;/*** * * @author Linux One leaf * just for testing use * */public class People {/*** * attribute variable * Age ages * Name name */private int age;private String name;/*** * Get Set method * @return */public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}

A very simple people object, in order to better understand and test.

Here is the main implementation of the single-instance code

package singleton;import java.util.concurrent.concurrenthashmap;import  Java.util.concurrent.concurrentmap;import singleton. people;/*** *  *  @author  linux One leaf  * *  @param  <t> */ The public class singleton<t> {/*** *  is stored using the Concurrenthashmap collection  * class   as a type of key ---object  * Object  instantiating as value---object  *  implementing the object's type and instantiating the object   one by one corresponds to  * /private static final concurrentmap<class, object> map = new  Concurrenthashmap<> ();/*** *  *  @param  type   incoming instantiated object type  *   @return  T  instantiation of the returned object  */public static<t>t getsingleton (class<t>  Type) {/*** *  the corresponding instance of the object from the map  *  *  to reduce operations on map, use local variable ob   here---  Conforming to optimization performance requirements  */object ob = map.get (type);try {/*** *  null judgment on an instance of the object  */if (ob==null) {/*** *  for using secure map and its operations    setting Sync lock  */synchronized  (map)  {/***  *  Create a new instance of the class represented by this  Class  object.  *  is like instantiating the class with an  new  expression with an empty argument list.  *  initializes this class if the class has not yet been initialized.   */ob=  type.newinstance ();/*** *  puts the object type and the new instance created into the Map */map.put (TYPE,OB);}} /****   is the two exception handling generated by Type.newinstance ()         *  * illegalaccessexception -  if the class or its  null  constructor method is inaccessible.  *InstantiationException -  If this  Class  represents an abstract class, interface, array class, * base type, or  void;  or the class does not have  null  Construction Method;  or for some other reason causes the instantiation to fail * * Do not do too much processing here */} catch  (instantiationexception e)  {e.printstacktrace ();}  catch  (illegalaccessexception e)  {e.printstacktrace ();} /*** *  Instantiate   Convert the object taken from the map to a generic parameter   return  */return   (T)  ob;} /*** *  the method   is to remove the object instantiation operation from the map  *  @param  type&nbSp;*/public static<t> void remove (class<t> type) {/*** * map Remove operation  */map.remove (type);}  public static void main (String[] args)  {/*** *  take people  as an example   Get its instantiation  */people str = singleton.getsingleton (people.class);/*** *  set test data  */ Str.setname ("Tom"); Str.setage (;/*** * ) Remove Test  *///singleton.remove (People.class); People s= singleton.getsingleton (People.class); System.err.println (S.getname () + "--" +s.getage ());}}

So far, my ideas have been shown with examples, focusing on collections and generic methods, dynamic maps need to be maintained manually, and if you like, you can add other map operations, such as put

Here is the difference between Java and C + + C #, there is no new T () in Java, and C + + C # can be directly new T () to do

Java-language generic programming implementation singleton mode

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.