Design Patterns learning notes-Singleton and Multiton)

Source: Internet
Author: User


Before model learning


What is the design model: when we design the program, we gradually formed some typical problems and solutions, which is the software model; each mode describes a problem that often occurs in our program design and the solution to the problem. When we encounter the problem described by the mode, the corresponding solution can be used to solve the problem. This is the design mode.

A design pattern is an abstract thing. It is not learned but used. Maybe you don't know any pattern at all, and you don't consider any pattern, but write the best code, even from the perspective of "pattern experts", they are all the best designs and have to say "best pattern practices". This is because you have accumulated a lot of practical experience, knowing "where to write code" is a design pattern.

Some people say: "If the level is not reached, you can learn it in vain. If the level is reached, you can do it yourself ". It is true that the mode is well-developed and may still not be able to write good code, let alone design a good framework. OOP understanding and practical experience reach a certain level, and it also means to summarize a lot of good design experience, however, it may not be the case that "no teacher can do anything", or you can say that, on the basis of level and experience, it is time for the system to learn the "mode, it is helpful to learn the experts' summary and verify your own shortcomings.

This series of design patterns learning notes is actually a Learning Record for the book "Java and patterns.


Singleton Mode


(1) A class has only one instance and is self-instantiated and provided to the entire system. This class is called a singleton class.
(2) One of the most important features of a singleton class is that the class constructor is private, thus avoiding the external use of constructor to directly create multiple instances.


Hungry Chinese Singleton type


Public class EagerSingleton {private static final EagerSingleton instance = new EagerSingleton (); private EagerSingleton () {}// static factory method public static EagerSingleton getInstance () {return instance ;}}


Lazy Singleton type


Public class LazySingleton {private static LazySingleton instance = null; private LazySingleton () {}// static factory method public static synchronized LazySingleton getInstance () {if (instance = null) {instance = new LazySingleton ();} return instance ;}}

Research on Dual-check Cases


To overcome the performance loss caused by synchronized (which avoids returning multiple instances in multi-threaded scenarios) in the lazy Singleton class, some people propose a dual-check example. The Code is as follows:

Public class DoubleCheckedSingleton {private static DoubleCheckedSingleton instance = null; private DoubleCheckedSingleton () {}// static factory method public static DoubleCheckedSingleton getInstance () {if (instance = null) {// multiple threads may arrive at synchronized (DoubleCheckedSingleton. class) {// only one thread can reach if (instance = null) {instance = new DoubleCheckedSingleton () ;}} return instance ;}} at the same time ;}}
This Code cannot work in Java, because in the Java compiler, the initialization of the DoubleCheckedSingleton class and the sequence of instance variable assignment are unpredictable, which may lead to a null pointer reference exception and cause program crash.


Learn more


(1) There is also an uncommon "registered Singleton category ";

(2) Singleton classes in JDK: java. lang. Runtime, java. awt. Tookit, javax. swing. TimerQueue, etc;

(3) Singleton mode and static class: although a class is composed of all static methods, all functions of Singleton mode can be fully implemented, however, only extremely common functions can be designed to be static. In other scenarios, Singleton should be used when "one class has only one instance. Static classes are not instantiated and are allocated to the Method Area memory when the system starts. This is a place where class structures, static attribute methods, and constant storage are located, it is also called "non-heap" and "permanent generation". When the Singleton is new, it is allocated to the heap memory.


Multiton Mode


As the object creation mode, multiple instance classes in the Multi-instance mode can have multiple instances, and multiple instance classes must create and manage their own instances and provide their own instances to the outside world.


Features of the Multi-sample mode


The so-called Multiton Pattern is actually a natural promotion of the Singleton Pattern. As the object creation mode, the multi-sample mode or multi-sample classes have the following features:

(1) Multiple instance types can have multiple instances

(2) You must create and manage your own instances and provide your own instances to the outside world.

(3) the maximum number of instances is divided into: the maximum number of instances and the maximum number of instances.


Multi-sample code example supported by one language

import java.util.*;class LingualResource{private String languages = "en";private String region = "US";private String localeCode = "en_US";private static final String FILE_NAME = "res";private static Map
 
   instances = new HashMap
  
   ();private Locale locale = null;private ResourceBundle resourceBundle = null;private LingualResource lingualResource;private LingualResource(String language,String region){this.localeCode = language;this.region = region;localeCode = makeLocaleCode(language,region);locale = new Locale(language,region);resourceBundle = ResourceBundle.getBundle(FILE_NAME,locale);instances.put(localeCode,this);}private LingualResource() {}public synchronized static LingualResource getInstance(String language,String region){if(instances.get(makeLocaleCode(language,region)) != null){return instances.get(makeLocaleCode(language,region));} else {return new LingualResource(language,region);}}public String getLocaleString(String code){return resourceBundle.getString(code);}private static String makeLocaleCode(String language,String region){return language + "_" + region;}}class LingualResourceTest{public static void main(String[] args){LingualResource lr = LingualResource.getInstance("en","US");String usDollar = lr.getLocaleString("USD");System.out.println("USD=" + usDollar);}}
  
 


Define an attribute file: res_en_US.properties, for example, USD = US Dollar.


A multi-sample format example of formatting numbers based on the language code and region code

import java.text.*;import java.util.*;class NumberFormatTest{public static void displayNumber(Double d,Locale l){NumberFormat nf;String dOut;nf = NumberFormat.getNumberInstance(l);dOut = nf.format(d);System.out.println(dOut + " " + l.toString());}public static void main(String[] args){displayNumber(1234567.89,new Locale("en","US"));displayNumber(1234567.89,new Locale("de","DE"));displayNumber(1234567.89,new Locale("fr","FR"));displayNumber(1234567.89,new Locale("zh","CN"));}}

Similarly, You Can format the currency (getCurrencyInstance) and the percentage (getPercentInstance) in the same way.


Summary of the Creation Mode (Creational Pattern)


There are a total of seven creation modes, namely simple factory mode, factory method mode, abstract factory mode, construction mode, prototype mode, Singleton mode, and multi-instance mode.


This article introduces two of them: singleton and Singleton.

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.