Java Project (5)--application and research of single-case model

Source: Internet
Author: User

Singleton mode is a very chic mode,very few people take it compared to other patterns .,because,Singleton mode is simple,It's special .,The function is to ensure that a class has a unique instance of,and let a global variable allow it to be accessed.The only way to ensure that this class is instantiated once is to turn the constructor into a private,but it's not the only one.NewNew Object,and then write the instantiation process in the class's own public method .,isNewThe new object is determined only by its own judgment .,already has an instance that directly returns an existing object,No, justNewa new instance.other classes want to instantiate an object Si cho this public method.

    • a hungry man type (pre- Initialize Object )
A hungry man type class Xmlconfigreader{private static Xmlconfigreader instance=new xmlconfigreader ();p rivate Xmlconfigreader () {} public static Xmlconfigreader getinstance () {return instance;}}
    • Lazy Type ( deferred initialization of objects )

  Lazy type (lazy load lazy) Class xmlconfigreader{    private static Xmlconfigreader instance =null;    public static synchronized Xmlconfigreader getinstance () {if (instance==null) {instance=new xmlconfigreader ();} return instance;}}


we often hear "Double-check Locking" that " Double Lock " the concept , that's because there's another way to lock it . , that uses Lock .

Class xmlconfigreader{private static Xmlconfigreader instance;private static ReadOnly Object Syncroot=new object (); Private Xmlconfigreader () {}public static Xmlconfigreader getinstance () {             if (instance==null) {Lock (syncRoot) {if ( Instance==null) {instance=new xmlconfigreader ();}}} return instance;}}

Compare :

The singleton pattern is divided into two categories , This method of static initialization is instantiated when the class is loaded , The first time you are referenced with a lazy-type is instantiated compared to pre-occupancy system resources ; but the lazy need to lock to ensure the security of multi-threaded access , a hungry man but no need . we have to choose the good person to use it ... ..

single application in the project :

DRP almost every module in the Manager , in the early stages of system development , because only Clientmanager , Use the singleton mode as follows :

public class Clientmanager {private static Clientmanager instance=new Clientmanager ();p rivate Clientmanager () {}public Static Clientmanager getinstance () {return instance;}}

with the increase of system complexity,there are more and moreManager,asItemmanager,flowcardmanagerwait,and this timeManagerwith theDaois separated.,There is a layered.The system employs an abstract factory+Reflection Technology ImplementationManagerClasses andDaoinstantiation of a class.The singleton is also used in the factory.

public class Beanfactory {private static beanfactory instance=new beanfactory ();p rivate final String beansconfigfile= " Beans-config.xml ";p rivate Document doc;private beanfactory () {try {doc=new saxreader (). Read (Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (Beansconfigfile));} catch (Documentexception e) {e.printstacktrace (); throw new RuntimeException ();}} public static Beanfactory getinstance () {return instance;}}

The following code is obtained in the factory classManagerpart of the singleton implementation.At first, I thought it was a meta-mode .,later found that this implementation is more flexible than the meta-mode.it guarantees that there is only one instance of the object,Therefore, the application of single-case mode.the more you get back, the more things you use.,is not confined to a certain pattern or technology.,enjoy RMB,Single Case,Factory,Agent...


Save service-related objects private Map servicemap=new HashMap ();/** * Get service products according to product number * @param Beanid * @return */public Synchroni Zed Object Getserviceobject (Class c) {//If there are related object instances, return if (Servicemap.containskey (C.getname ())) {return Servicemap.get ( C.getname ());} Element beanelt= (Element) Doc.selectsinglenode ("//service[@id =\" "+ c.getname () +" \ "]"); String Classname=beanelt.attributevalue ("class"), Object service=null;try {service=class.forname (className). Newinstance ();//Put the created object into map Servicemap.put (C.getname (), service);} catch (Exception e) {throw new RuntimeException ();} return service;}


through the above analysis and application , Another look at the focus of the singleton model :

implementation on , private static member variable / Private Construction Methods / the public static method ; resolves problems with global access and instantiation control .

the meaning of the singleton is not to create,rather, it is access,Which means,the object to access or invoke, if it does not exist, creates a,This is the only one,can no longer be created after;returns the object if it exists,Although the property of the object has been changed countless times because it has been re-assigned,The object is unique, but not immutable..


Java Project (5)--application and research of single-case model

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.