官术网_书友最值得收藏!

Creating classes based on singleton design pattern

A singleton class is a class that can have only one instance at a time. Any attempt to create a second or more instances should not be allowed. This recipe shows how to create a class based on the singleton design.

Getting ready

We will use the same class created in the last recipe of factory method. We will make few changes to the class so that we can prevent the creation of multiple instances of the class. We will make a copy of the class (program) shown in the previous recipe and modify it. The name of the copy is singleton_class.

How to do it...

For creating a singleton class, follow these steps:

  1. Make sure the CREATE PRIVATE addition is included in the singleton class definition.
  2. Within the definition, a static attribute number_of_instances having type integer is added to the private section.
    How to do it...
  3. The implementation of the class is then written. The factory method has to be slightly modified in order to force the singleton characteristic.
    How to do it...
  4. In the implementation of the singleton class, the factory method now contains an IF statement that first checks the number of instances already there when the factory call is made. If the first instance is being created (that is, number_of_instances equals 0), the employee object is created and number_of_instances is set as 1. An ELSE condition is included to output a message if one instance already exists.
    How to do it...

How it works...

Similar to the previous recipe, we try to instantiate two objects emp1 and emp2, having number 0000012 and 00000014 respectively. However, in our singleton class, we have added an attribute number_of_instances, which keeps track of the number of class instances that already exist. Upon creation of the first object, the factory method increments this static attribute to 1. On the second object creation attempt, the IF statement does not allow the CREATE OBJECT statement to be called a second time. The result is that the second object is not created. No further attempts of object creation will be allowed. Rather, a message saying that only one object instantiation is allowed is outputted for the second object creation attempt.

How it works...
主站蜘蛛池模板: 邵阳市| 元朗区| 抚宁县| 隆德县| 浦城县| 白银市| 桃园县| 都安| 泸州市| 凌云县| 迭部县| 顺昌县| 夏河县| 商水县| 惠安县| 万安县| 富裕县| 贡嘎县| 武陟县| 府谷县| 吉林省| 福泉市| 苏尼特右旗| 黔西| 雷波县| 杭锦旗| 三河市| 武义县| 汪清县| 武宣县| 博乐市| 萨嘎县| 南投县| 定结县| 松滋市| 望江县| 连云港市| 长葛市| 团风县| 白银市| 江门市|