Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Singleton design pattern of design pattern

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

SINGLETON (singleton)-object creation mode

1. Intention

Ensure that there is only one instance of a class and provide a global access point to it.

two。 motivation

For some classes, only one instance is important. Although there can be many printers in the system, there should be only one print spooling (printer spooler), only one file system and one window manager. A digital filter can only have one A / D converter. An accounting system can only be dedicated to one company.

How can we ensure that there is only one instance of a class and that this instance is easy to access? A global variable makes an object accessible, but it does not prevent you from instantiating multiple objects. A better approach is to make the class itself responsible for saving the only instance of it. This class ensures that no other instance can be created (by intercepting requests to create new objects), and it can provide a method to access the instance. This is the S i n g l e t o n mode.

3. Applicability

S i n g l e t o n mode can be used in the following cases

When a class can have only one instance and the customer can access it from a well-known access point.

When this unique instance should be extensible by subclassing, and the customer should be able to use an extended instance without changing the code.

Applicable scenarios:

In the future, the system will have high concurrency, such as dbinfo, the database information will be put in the configuration file, and the high concurrency function is to read the configuration file only once.

Dbinfo

Servlet

Listener

Filter

Note: request and response are not singleton objects. Everyone accesses the same servlet, but the difference is that everyone's request request is different, and the request object is created by the servlet container. The request object is bound to a HTTP request, and a HTTP request is bound to a request.

Application is a global variable and a singleton object.

4. structure

5. Participant

S i n g l e t o n

-defines an I n s t a n c e operation that allows customers to access its unique instance. I n s t a n c e is a class operation (that is,

A class method in S m a l l t a l k and a static member function in C + +.

-may be responsible for creating its own unique instance.

6. Collaboration

Customers can only access one instance of S i n g l e t o n through the I n s t a n c e operation of S i n g l e t o n.

7. Realize

There are two ways to write a common single case:

Write method 1:

Public class ConnectionFactory {private static ConnectionFactory factory; / / Singleton private DbInfo dbinfo; private ConnectionFactory (DbInfo dbinfo) {this.dbinfo = dbinfo;} public static ConnectionFactory instance () {if (factory = = null) {DbInfo dbinfo = DbInfo.instance () Factory = new ConnectionFactory (dbinfo);} return factory;} / * Open a database connection * @ return * / public DbConnection openConnection () {DbConnection connection If (this.dbinfo.getDriver (). Equals ("oracle")) {connection = new OracleConnection (factory);} else {connection = new MysqlConnection (factory);} return connection;}}

Writing method 2:

Public class ConnectionFactory2 {private static ConnectionFactory2 factory; / / 1. To have a singleton object private ConnectionFactory2 () {} static {factory = new ConnectionFactory2 ();} public static DbConnection openConnection () {DbConnection connection DbInfo dbinfo = DbInfo.instance (); if (dbinfo.getDriver (). Equals ("oracle")) {connection = new OracleConnection (factory);} else {connection = new MysqlConnection (factory);} return connection }}

Thread-related singleton writing:

/ / hungry Han style. (commonly used)

Class Single {private static final Single s = new Single (); private Single () {} public static Single getInstance () {return s;}}

/ / lazy style (delayed loading singleton design pattern)

Class Single {private static Single s = null; private Single () {} public static Single getInstance () {if (s==null) {/ / multiple judgment synchronized (Single.class) {/ / Note the use of lock if (s==null) s = new Single ();}} return s;}}

The singleton model has the following characteristics:

1. A singleton class can only have one instance.

2. The singleton class must create its own unique instance.

3. The singleton class must provide this instance to all other objects.

8. Parse the contents of the database configuration file (file configuration, xml configuration) into a singleton object

01. Parse configuration file

Configuration file

DbURL=jdbc:oracle:thin:@10.0.19.252:1521:orcldbDriver=oracle.jdbc.driver.OracleDriverusername=motopassword=123456

Singleton class

Public class DbInfo {private static DbInfo dbInfo; / / Singleton private String dbURL; private String dbDriver; private String username; private String password Private DbInfo () {} public static DbInfo instance () throws Exception {if (dbInfo = = null) {dbInfo = new DbInfo (); dbInfo.init ();} return dbInfo Read the configuration file and initialize * / private void init () throws Exception {Properties prop = new Properties (); String path = DbInfo.class.getResource ("/"). GetPath () + "db.properties"; prop.load (new FileInputStream (new File (path) This.dbDriver = prop.getProperty ("dbDriver"); this.dbURL = prop.getProperty ("dbURL"); this.password = prop.getProperty ("password"); this.username = prop.getProperty ("username");} public String getDbURL () {return dbURL } public String getDbDriver () {return dbDriver;} public String getUsername () {return username;} public String getPassword () {return password;}}

02. Parsing xml files

Xml file

Jdbc:oracle:thin:@10.0.19.252:1521:orcl oracle.jdbc.driver.OracleDriver moto 123456

Singleton class

Public class DbInfo2 {private static DbInfo2 dbInfo; / / Singleton private String dbURL; private String dbDriver; private String username; private String password; private Document document Private DbInfo2 () {} public static DbInfo2 instance () throws Exception {if (dbInfo = = null) {dbInfo = new DbInfo2 (); dbInfo.init ();} return dbInfo Read the configuration file and initialize * / private void init () throws Exception {String path = DbInfo.class.getResource ("/"). GetPath () + "config.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); DocumentBuilder db = dbf.newDocumentBuilder () Document = db.parse (new File (path)); / / parse the XML file Node node = document.getElementsByTagName ("DbInfo") .item (0); Element element = (Element) node; dbURL = element.getAttribute ("dbUrl") DbDriver = element.getAttribute ("dbDriver"); this.username = element.getAttribute ("username"); this.password = element.getAttribute ("password");} public String getDbURL () {return dbURL;} public String getDbDriver () {return dbDriver } public String getUsername () {return username;} public String getPassword () {return password Read the configuration file and initialize * / / parse / / private void init () throws Exception {String path = DbInfo.class.getResource ("/"). GetPath () + "config.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); DocumentBuilder db = dbf.newDocumentBuilder (); document = db.parse (new File (path)) / / parse the XML file Node node = document.getElementsByTagName ("DbInfo") .item (0); Element element = (Element) node; dbURL = element.getAttribute ("dbUrl"); dbDriver = element.getAttribute ("dbDriver"); this.username = element.getAttribute ("username") This.password = element.getAttribute ("password");}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report