經過枚舉enum實現單例設計

1、枚舉java

      經過enum關鍵字來實現枚舉,在枚舉中須要注意的有:mysql

        1. 枚舉中的屬性必須放在最前面,通常使用大寫字母表示sql

        2. 枚舉中能夠和java類同樣定義方法數據庫

        3. 枚舉中的構造方法必須是私有的ide

       經過一個java類來模擬枚舉的功能:性能

   

package org.lkl.imitate_enum;

public abstract class WeekDay {
    public static final WeekDay SUN = new WeekDay() {

        @Override
        public WeekDay nextDay() {
            return MON;
        }
    };
    public static final WeekDay MON = new WeekDay() {

        @Override
        public WeekDay nextDay() {
            return SUN;
        }

    };
 
    @Override
    public String toString() {
        return this == SUN ?"SUN星期天":"MON星期一" ;
    }

    public abstract WeekDay nextDay();

    public static void main(String[] args) {
          System.out.println(WeekDay.SUN.nextDay());
          System.out.println(WeekDay.MON.nextDay());
    }
}

         4.能夠在枚舉屬性後面添加()來調用指定參數的構造方法,添加{}來實現其對應的匿名內部類,例如: 測試

package org.lkl.imitate_enum;
public enum TrafficLamp {
    RED(30){
        public  TrafficLamp nextLamp() {
            return GREEN ;
        }
    },
    GREEN(20){
        public  TrafficLamp nextLamp() {
            return YELLOW ;
        }
    },
    YELLOW(10){
        public  TrafficLamp nextLamp() {
            return RED ;
        }
    } ;
    public abstract TrafficLamp nextLamp() ;
    private int time ;
    private TrafficLamp(int time){
        this.time = time ;
        System.out.println(time);
    }
    
    public static void main(String[] args) {
        System.out.println(TrafficLamp.GREEN);
    }
}

2、經過枚舉來實現單例ui

      實現單例的核心在於private私有化類中的構造方法,在枚舉中的構造方法必須是私有的,這就爲枚舉來實現單例奠基了基礎。下面以數據源中得到Connection鏈接來舉例:this

      在開發中常常是經過數據源來得到數據庫的Connection,數據源的實現方式有多種,最典型的有兩種,一種是C3P0,另一種是DBCP(之後有機會再針對兩種數據源進行討論),這裏以C3P0數據源爲例。因爲數據源的建立與銷燬都是十分消耗性能的,而且系統中有一個數據源通常就能知足開發的要求,所以要將數據源設計爲單例。spa

     採用分散配置,建立一個jdbc.propertis文件,其內容以下:

    

driverClass = com.mysql.jdbc.Driver
jdbcUrl = jdbc:mysql://localhost:3306/liaokailin
user = root
password = mysqladmin
maxPoolSize = 20
minPoolSize = 5

   建立一個MyDataBaseSource的枚舉:

package org.lkl.imitate_enum;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public enum MyDataBaseSource {
    DATASOURCE;
    private ComboPooledDataSource cpds = null;

    private MyDataBaseSource() {
        try {

            /*--------獲取properties文件內容------------*/
            // 方法一:
            /*
             * InputStream is =
             * MyDBSource.class.getClassLoader().getResourceAsStream("jdbc.properties");
             * Properties p = new Properties(); p.load(is);
             * System.out.println(p.getProperty("driverClass") );
             */

            // 方法二:(不須要properties的後綴)
            /*
             * ResourceBundle rb = PropertyResourceBundle.getBundle("jdbc") ;
             * System.out.println(rb.getString("driverClass"));
             */

            // 方法三:(不須要properties的後綴)
            ResourceBundle rs = ResourceBundle.getBundle("jdbc");
            cpds = new ComboPooledDataSource();
            cpds = new ComboPooledDataSource();
            cpds.setDriverClass(rs.getString("driverClass"));
            cpds.setJdbcUrl(rs.getString("jdbcUrl"));
            cpds.setUser(rs.getString("user"));
            cpds.setPassword(rs.getString("password"));
            cpds.setMaxPoolSize(Integer.parseInt(rs.getString("maxPoolSize")));
            cpds.setMinPoolSize(Integer.parseInt(rs.getString("minPoolSize")));
            System.out.println("-----調用了構造方法------");
            ;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection() {
        try {
            return cpds.getConnection();
        } catch (SQLException e) {
            return null;
        }
    }

}

測試代碼:

package org.lkl.imitate_enum;

public class Test {
    public static void main(String[] args) {
        MyDataBaseSource.DATASOURCE.getConnection() ;
        MyDataBaseSource.DATASOURCE.getConnection() ;
        MyDataBaseSource.DATASOURCE.getConnection() ;
    }
}

結果以下:

-----調用了構造方法------
2013-7-17 17:10:57 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge16d8v1tgb0wppydrzz|2c1e6b, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge16d8v1tgb0wppydrzz|2c1e6b, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/kaoqin, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 5, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]

很顯然得到了三個Connection鏈接,可是隻調用了一次枚舉的構造方法,從而經過枚舉實現了單例的設計

相關文章
相關標籤/搜索