"Object Performance" mode of C + + design mode: Singleton, Flyweight

Source: Internet
Author: User

  "Object Performance" mode
Object-oriented is a good solution to the "abstract" problem, but it must be paid a certain price. In general, object-oriented costs are largely negligible. In some cases, however, object-oriented costs must be handled with care.

  Typical mode
# Singleton
# Flyweight

  Part 1 Single-piece mode (single-case mode )

  Motivation
#在软件系统中, there are often special classes that must be guaranteed to have only one instance of the system in order to ensure their logical correctness and good efficiency.
#如何绕过常规的构造器, provides a mechanism to guarantee that there is only one instance of a class?
#这应该是类设计者的责任, not the responsibility of the user.

  Pattern definition
Ensure that a class has only one instance and provides a global access point for that instance. --"Design pattern" GoF

  Code

classsingleton{Private StaticSingleton instance; Private Static ReadOnly ObjectSyncRoot =New Object();  Public StaticSingleton getinstance () {if(Instance = =NULL)        {            Lock(syncRoot) {if(Instance = =NULL) Instance=NewSingleton (); }        }                returninstance; }        Private StaticSingleton instance () {}}

  Structure
  

  Summary of Points
# The instance constructor in Singleton mode can be set to protected to allow subclasses to derive.
# Singleton mode generally does not support copy constructors and Clone interfaces, because this can lead to multiple object instances, contrary to the original intention of the Singleton mode.
#如何实现多线程环境下安全的 Singleton? Note the correct implementation of the double check lock.

"Object Performance" mode of C + + design mode: Singleton, Flyweight

Related Article

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.