<! -- @ Page {margin: 0.79in} P {margin-bottom: 0.08in} H1 {margin-bottom: 0.08in} H1.western {font-family: "Liberation Sans", sans-serif; font-size: 16pt} H1.cjk {font-family: "ar pl UMing HK"; font-size: 16pt} H1.ctl {font-family: "Lohit Hindi"; font-size: 16pt} -->
Java
Three options
1) use a common class
There are public constructors and no member variables. Many member functions are provided as methods. The call code is as follows:
Helper helper = new Helper ();
Helper. f1 ();
The disadvantage of this method is that the cost of creating an object is unnecessary. We know that creating an object means that we need to allocate memory first and then create an object on the memory. In a scenario where a large number of helper objects are created, this burden is huge.
2) To avoid the overhead of repeated object creation, we can use the Singleton delay creation technology to ensure that there is only one object in the process and it will be created only when it is called for the first time.
Helper helper = Helper. getInstance ();
Helper. f1 ();
This method has improved a lot, but it still has shortcomings. This causes many Singleton classes in the system. In fact, Singleton is mainly used to express the unique objects in the system. Generally, these objects are stateful. Too many Singleton systems designed for other purposes may confuse developers.
3) A common class provides static method access and the constructor is private. At the same time, modifying the class with the final keyword indicates that the class cannot be inherited.
Helper. f1 ();
Because of the private constructor, you cannot directly create an object or create a subclass object after the quilt class is inherited. If necessary, you can also throw an exception in the private constructor to prevent reflection attacks.
I think this is the best solution in Java.
C ++
Same reasoning and same conclusion. However, the Code check tool is missing in C ++. If you forget to convert the constructor into private, the Java check tool will usually remind you. C ++ can only be solved by coding specifications. In addition, C ++ does not have the final keyword to indicate that the class cannot be inherited.