"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