Android design mode: Singleton mode; android Design Mode

Source: Internet
Author: User

Android design mode: Singleton mode; android Design Mode

Design Patterns are some of the experiences accumulated by our predecessors during the development process. During the development process, we apply appropriate design patterns based on actual conditions to make the program structure simpler, it is conducive to program expansion and maintenance, but it is not difficult to use a program without a design pattern. For example, a simple program is no longer needed, and there is a feeling of being superfluous.

The Singleton mode is the simplest of all modes. It can only create one instance from start to end. It can be in two forms: lazy and hungry.

I. Ele. Me is simple. I created an instance from the very beginning. In fact, whether it will be called or not

Package com. dzt. singleton;/*** hunger, thread security ** @ author Administrator **/public class SingletonHungry {private static SingletonHungry instance = new SingletonHungry (); private SingletonHungry () {} public static SingletonHungry getInstance () {return instance ;}}
2. In the lazy way, because the thread is not secure, there may be problems in multi-thread processing, So synchronization is required.

Package com. dzt. singleton;/*** lazy, this is thread unsafe. If multiple threads are running, multiple instances may be created ** @ author Administrator **/public class SingletonIdler {private static SingletonIdler instance = null; private SingletonIdler () {} public static SingletonIdler getInstance () {if (instance = null) {instance = new SingletonIdler () ;}return instance ;}}
After the synchronization code is added, You must judge the synchronization lock every time you come in. This is time-consuming and can be improved.

Package com. dzt. singleton;/*** lazy ** @ author Administrator **/public class SingletonIdler {private static SingletonIdler instance = null; private SingletonIdler () {} public synchronized static SingletonIdler getInstance () {if (instance = null) {instance = new SingletonIdler () ;}return instance ;}}
Add a synchronization code block and only judge the synchronization once. If you have created an instance, the synchronization will not be judged, reducing the time.

Package com. dzt. singleton;/*** lazy ** @ author Administrator **/public class SingletonIdler {private static SingletonIdler instance = null; private SingletonIdler () {} public static SingletonIdler getInstance () {if (instance = null) {synchronized (SingletonIdler. class) {if (instance = null) instance = new SingletonIdler () ;}} return instance ;}}
The Singleton mode is also used in Android native applications, such as Phone.

NotificationMgr. java class

private static NotificationMgr sInstance;private NotificationMgr(PhoneApp app) {mApp = app;mContext = app;mNotificationManager = (NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE);mStatusBarManager = (StatusBarManager) app.getSystemService(Context.STATUS_BAR_SERVICE);mPowerManager = (PowerManager) app.getSystemService(Context.POWER_SERVICE);mPhone = app.phone; // TODO: better style to use mCM.getDefaultPhone()// everywhere insteadmCM = app.mCM;statusBarHelper = new StatusBarHelper();}static NotificationMgr init(PhoneApp app) {synchronized (NotificationMgr.class) {if (sInstance == null) {sInstance = new NotificationMgr(app);// Update the notifications that need to be touched at startup.sInstance.updateNotificationsAtStartup();} else {Log.wtf(LOG_TAG, "init() called multiple times!  sInstance = "+ sInstance);}return sInstance;}}


What is the singleton design model?

Java mode Singleton mode:
Singleton mode ensures that a class has only one instance and provides the instance to the entire system.
Features:
1. One class can only have one instance
2. Create the instance by yourself.
3. The entire system uses this instance.
For example, in the following object diagram, there is a "singleton object ", "Customer A", "Customer B", and "customer C" are the three customer objects of the singleton object. As you can see, all customer objects share one singleton object. In addition, we can see from the singleton object to its own connection line that the singleton object holds a reference to itself.

The Singleton mode ensures that only one instance of a Class exists in a Java application. In many operations, such as creating a directory database connection, such single-threaded operations are required. Some resource managers are often designed to work in singleton mode.
External resources: for example, each computer may have several printers, but only one Printer Spooler can be used to prevent two print jobs from being output to the Printer at the same time. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being called by both requests at the same time. For example, most software has one or more attribute files to store system configurations. Such a system should be managed by an object.

Example: Windows recycle bin.
In the entire Windows system, the recycle bin can only have one instance, and the entire system uses this unique instance, and the recycle bin provides its own instance. Therefore, the recycle bin is a singleton application.

Two forms:
1. Hunger type Singleton
Public class Singleton {

Private Singleton (){}

// Define your own instance internally. Isn't it strange?
// Note that this is private for internal calls only

Private static Singleton instance = new Singleton ();

// Here is a static method for external access to this class, which can be accessed directly.
Public static Singleton getInstance (){
Return instance;
}
}

2. Lazy Singleton type

Public class Singleton {

Private static Singleton instance = null;

Public static synchronized Singleton getInstance (){

// This method is better than above. You don't need to generate objects every time. It's just the first time.

// Generate instances during use, improving efficiency!
If (instance = null)
Instance = new Singleton ();
Return instance ;}

}

The second form is lazy initialization. That is to say, the initial Singleton is used for the first call and will not be regenerated in the future .... Remaining full text>

What design patterns are familiar to you? Write the implementation code of Singleton Mode

There are 23 design modes in total!

Reference the "software secrets-the point of design patterns" book:

According to the purpose, the design patterns can be divided into creation patterns, structural patterns, and behavior patterns.
The creation mode is used to process the object creation process, the structure mode is used to process the combination of classes or objects, and the behavior mode is used to describe how classes or objects interact and how responsibilities are assigned.

The creation mode is used to process the object creation process. It mainly includes the following five design modes:
Factory Method Pattern)
Abstract Factory Pattern)
Builder Pattern)
Prototype Pattern)
Singleton Pattern)

The structural mode is used to process the combination of classes or objects. It mainly includes the following seven design modes:
Adapter Pattern)
Bridge Pattern)
Composite Pattern)
Decorator Pattern)
Facade Pattern)
Flyweight Pattern)
Proxy Pattern)

The behavior pattern is used to describe how classes or objects interact and how responsibilities are assigned. It mainly includes the following 11 design patterns:
Chain of Responsibility Pattern)
Command Pattern)
Interpreter mode (Interpreter Pattern)
Iterator Pattern)
Mediator Pattern)
Memory memorandum mode (Memento Pattern)
Observer Pattern)
State Pattern)
Strategy Pattern)
Template Method Pattern)
Visitor Pattern)

Singleton mode Implementation 1:
Public class Singleton {
// Class shared Instance Object
Private static Singleton singleton = null;
// Private constructor
Private Singleton (){
System. out. println ("-- this is Singleton !!! ");
}
// Obtain the singleton Method
Public synchronized static Singleton getInstance (){
// Determine whether the shared object is null. If it is null, a new object is created.
If (singleton = null ){
Singleton = new Singleton ();
}
Return singleton;
}
}

Singleton mode implementation 2:
Public class Singleton {
// Class shared Instance Object Instantiation
Private s... the remaining full text>

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.