Ruby design mode Dialysis: Single case (Singleton)

Source: Internet
Author: User
Tags instance method


Write software often need to use the Print log function, can help you debug and positioning problems, the project on the line can also help you analyze the data, but Ruby native with the puts method is rarely used in real project development.



Why is the puts of the new Ruby artifact going to be spurned in real project development? In fact, as long as the careful analysis, you will find many of its drawbacks. such as uncontrollable, all logs will be printed as usual after the project is online, to reduce operational efficiency; Or you cannot log to a local file, and once the print is cleared, the log will never be able to find it again, or if the printed content is not tagged, you will find it difficult to tell which class the log is printed in.



Your leader is also not a fool, with puts of the various drawbacks he also clearly, so he gave you today's task is to create a log tool class, to provide better logging capabilities. But your leader is not bad, and does not allow you to start with a function of the great Log tool class, only need to control the printing level log tool.



This requirement is not difficult for you, you immediately began to write, and soon completed the first version:


Class Logger  
    DEBUG = 0
    INFO = 1
    ERROR = 2 Nothing
    = 3 level
          
    = Debug
          
    def DEBUG msg  
        puts msg if DEBUG >= level
    end
          
    def info msg  
        puts msg if info >= level
    end
          
    def error msg  
        puts msg if ERROR >= level
    End


This class is used to print the log, and you can control the printed content freely by simply controlling level levels. For example, now that the project is in the development phase, the level is set to debug so that all log information will be printed. And the project if the line, you can set the level to info, so you can only see the info and above the log printing. If you only want to see the error log, you can set the level as error. And if you develop a project that is a client version and you don't want any log to print, you can set the level to nothing. When printing, you only need to call:


Logger = logger.new
logger.debug ("Hello World")


You can not wait to introduce this tool to your leader, your leader after listening to your introduction, said: "Good, the future everyone will use you write this tool to print the log!" ”



But not long after, your leader find you to feedback the question. He said that although this tool is easy to use, but the printing of this kind of thing is not a distinction between objects, here every time need to print a log of the need for a new logger, too much memory, I hope you can change this tool into a single example mode.



You think your leader is making a lot of sense, and you want to take this opportunity to practice using design patterns, so you write the following code:


Class Logger  
    private_class_method:new
          
    debug = 0
    INFO = 1
    ERROR = 2 Nothing
    = 3 level
          
    = Debug
          
    @ @instance = nil
          
    def debug msg  
        puts msg if debug >= level
    end
          
    def info msg  
        puts msg if info > = Level
    End
          
    def error msg  
        puts msg if error >= level
    end
          
    def self.instance  
        @ @instance = New unless @ @instance
    end


First use Private_class_method to privatize the logger new method, so that you cannot create an instance of logger by using the new method. It then uses a static variable @ @instance to save the instance and provides a public instance method for obtaining an instance of the logger, in which it is judged that if the @ @instance is nil, a new logger instance is created, otherwise return directly to @ @instance. This ensures that only one logger instance is present in memory. Single Case mode completed! The code for the print log needs to be changed to the following ways:


Logger = logger.instance  
logger.debug ("Hello World")


You will show this version to your leader see, he smiled and smiled, said: "Well, yes, the function is realized." But there's a simpler way to implement it on Ruby. ”



I saw him skillfully tapping the keyboard to show you a simpler way to implement a single implementation (modified on the basis of the original code).


Require ' singleton '
class Logger  
    include singleton  
          
    #Omit the remaining code End


First, introduce the SINGLETON.RB file from the system configuration path, and then introduce the Singleton module in the Logger class. OK, it's all finished!



"What?! "You simply don't believe your eyes, you just add two lines of code to complete the single case pattern." "But where does the instance approach come from?" ”



Your leader tells you that Ruby has a modular (module) mechanism in which the class can access the methods defined in the module after it has been introduced into the class. The instance method is defined in the Singleton module and then introduced into the module at runtime, and the logger class can access the instance method in Singleton.



Singleton: guarantees that a class has only one instance and provides a global access point to access it.



See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/project/


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.