In. net Personal Edition Data room charging system, such as form instantiation, class calling in layer B abstract factory to instantiate factory classes (to create excuses), sqlhelper calls, etc, the abstract factory called in the Personal Edition is instantiated every time the abstract factory needs to be called. For example:
Dim factory as new dbfactory 'instantiate the factory variable dim isboolean as Boolean dim iuser as iuser = factory. createuser () 'to call the factory to create an interface
In this way, there is no problem from the perspective of function implementation, but from the perspective of memory usage, each instantiation requires the memory to allocate a memory space for it, during this program running process, you may need to call the factory to create an excuse. For the same class, too much instantiation not only wastes memory space, but also reduces the overall execution efficiency of the program,
After learning the design mode, we considered that the singleton mode can solve this problem: ensure that a class has only one instance and provide a global access point to it.
Code after the singleton mode is added:
Private shared instance as dbfactory defines a static factorydatabase object private shared readonly padlock as new object () 'defines static read-only object private sub new () 'Private constructor end sub' instantiation method public shared function getinstance () as dbfactory 'dual lock prevents multithreading from instantiating the same object if isnothing (Instance) then synclock padlock if isnothing (Instance) Then instance = new dbfactory () end if end synclock end if return instance end Function
Although the singleton mode can ensure that a class instantiates an object, if this class is multi-threaded, multiple instantiated objects may appear, So we add lock, make sure that when a thread is located in the critical section of the Code, the other thread does not enter the critical section, and other threads attempt to enter the locked code. It waits (that is, it is blocked) until the object is released.
The Singleton mode can be used in two ways: ele. Me Khan type singleton and lazy type Singleton type ele. Me type Singleton can be instantiated when the static initialization method is loaded; the lazy style will instantiate itself when it is referenced for the first time. The specific usage is determined based on actual needs to ensure data security.
The use of design patterns greatly improves the execution efficiency of our programs and optimizes our code. Requirements for other design patterns ......