隨筆 - 40, 文章 - 0, 評論 - 20, 引用 - 0
          數據加載中……

          Ibatis示例


          1.將ibatis 的jar 包添加到工程中

          2.先新建一個xml文件 SqlMap.xml,在這個文件中定義使用了哪些ibatis資源文件
          <?xml version="1.0" encoding="gb2312"?>
          <!DOCTYPE sql-map-config PUBLIC "-//iBATIS.com//DTD SQL Map Config 1.0//EN"
              "<sql-map-config>
            <sql-map  resource="com/montersoft/ibatis/common/monter.xml"/>
          </sql-map-config>

          3.定義資源文件monter.xml
          <?xml version="1.0" encoding="gb2312"?>
          <!DOCTYPE sql-map
              PUBLIC "-//iBATIS.com//DTD SQL Map 1.0//EN"
              "
          <sql-map name="monter">
             <result-map name="monterInfo" class="java.util.HashMap">
               <property name="id"  column="id" type="VARCHAR"/>
               <property name="name" column="name" type="VARCHAR"/>
               <property name="age"  column="age"  type="NUMBERIC"/>
             </result-map>  
             <dynamic-mapped-statement name="monter_getByPk" result-map="monterInfo">
             select id,name,age from monter where id = #id#
             </dynamic-mapped-statement>
          </sql-map>

          **注意dynamic-mapped-statement的name 必須唯一

          4.定義一個公共類來生成SqlMap
          package com.montersoft.ibatis.common;
          import java.io.Reader;
          import org.apache.commons.logging.Log;
          import org.apache.commons.logging.LogFactory;
          import com.ibatis.common.resources.Resources;
          import com.ibatis.db.sqlmap.SqlMap;
          import com.ibatis.db.sqlmap.XmlSqlMapBuilder;
          public class SqlMapUtil { 
           private static Log loger = LogFactory.getLog(SqlMapUtil.class);
           public  static SqlMap  sqlMap ; 
           public static SqlMap loadSqlMap(){
            Reader reader = null;
            try{
             reader = Resources.getResourceAsReader("com/montersoft/ibatis/common/SqlMap.xml");
             return XmlSqlMapBuilder.buildSqlMap(reader);
            }
            catch(Exception e){   
             loger.error("there is a error=>"+e.getMessage());
            }
            return null;
           } 
           public static SqlMap getSqlMap(){
            if( sqlMap == null )
             sqlMap = loadSqlMap();
            return sqlMap;
           } 
          }
          5.再新建DAO,Vo,
          public interface  IVO { 
          }
          public class MonterVo implements IVO{ 
           public String id ;
           public String name;
           public int age;
           ...省去 get ,set 方法
          }
          public class MonterDao { 
             public IVO getBkPK(Connection conn,IVO vo) throws Exception{
              try{    
              Object map  =  SqlMapUtil.getSqlMap().
                 getMappedStatement("monter_getByPk").executeQueryForObject(conn,vo);
              return   copyMap2Vo(map);
              }
              catch(Exception e){       
                  throw new Exception(e.getMessage());
              }
             }  
             private IVO copyMap2Vo(Object map){
              MonterVo vo = new MonterVo();
            try{
             BeanUtils.copyProperties(vo,map);
            }
            catch(Exception e){
             e.printStackTrace();
            }
            return vo;
           }
          }

          6.至此就建立了一個簡單的ibatis示例.

          posted @ 2006-01-06 16:39 月亮 閱讀(329) | 評論 (0)編輯 收藏

          通過weblogic的數據源獲得數據庫連接的方法

          通過weblogic的數據源獲得數據庫連接的方法:

          package com.moonsoft.datasource;

          import javax.naming.NamingException;
          import java.util.Hashtable;
          import javax.naming.InitialContext;
          import java.sql.Connection;
          import javax.sql.DataSource;
          import java.sql.SQLException;
          import java.sql.PreparedStatement;
          import java.sql.ResultSet;

          public class TestDataSource {

            public static String WEB_URL = "t3://localhost:9000";
            public static String DATA_SOURCE = "JDBCDS";
            public static String weblogic_context_factory =
                "weblogic.jndi.WLInitialContextFactory";
            public TestDataSource() {
            }
            public static Object lookUp() throws NamingException {
              Hashtable env = new Hashtable();
              env.put(InitialContext.INITIAL_CONTEXT_FACTORY, weblogic_context_factory);
              env.put(InitialContext.PROVIDER_URL, WEB_URL);
              InitialContext tempContext = new InitialContext(env);
              return tempContext.lookup(DATA_SOURCE);
            }
            public static Connection getConnection() throws SQLException {
              Connection conn = null;
              try {
                DataSource ds = (DataSource) lookUp();
                if (ds == null) {
                  throw new SQLException("查詢到空數據源!");
                }
                conn = ds.getConnection();
              }
              catch (NamingException ex) {
                ex.printStackTrace();
              }
              return conn;
            }
            public static void releaseConnection(Connection conn, PreparedStatement sta,
                                                 ResultSet rs) {
              try {
                if (rs != null) {
                  rs.close();
                }
                if (sta != null)
                  sta.close();
                if (conn != null)
                  conn.close();
              }
              catch (Exception ex) {
                ex.printStackTrace();
              }
            }
            public static void testSearch() {
              Connection conn = null;
              PreparedStatement sta = null;
              ResultSet rs = null;
              try {
                conn = getConnection();
                String sql = "select * from admin_config where config_name like ?";
                sta = conn.prepareStatement(sql);
                sta.setString(1,"%Sms%");
                rs = sta.executeQuery();
                if (rs != null) {
                  while (rs.next()) {
                    System.out.println(rs.getString(1));
                  }
                }
              }
              catch (Exception ex) {
                ex.printStackTrace();
              }
              finally {
                releaseConnection(conn,sta,rs);
              }
            }
            public static void main(String [] argv){
              testSearch();
            }
          }

          posted @ 2006-01-05 10:51 月亮 閱讀(1239) | 評論 (0)編輯 收藏

          一個設計中使用比較多的模式

          如果是在需求還沒確定或者是在兩個類實現相近功能時候,會大量使用下面的方式:
          --抽象類,注意其中的newInstance方法的實現
          package com.moonsoft.design;
          public  abstract class Moon {
            public static Moon newInstance(String classStr){
              Class re;
              try {
                re =  Class.forName(classStr);
                return (Moon)re.newInstance();
              }
              catch (Exception ex) {
                ex.printStackTrace();
              }
              return null;
            }
            public abstract void  println();
          }
          --從Moon類派生出來的一個字類,提供println方法的一種實現方式
          package com.moonsoft.design;
          public class Moon1 extends Moon {
            public void println(){
              System.out.println("I am moon1");
            }
            public void myprintln(){
              System.out.println("I am moon1 myprintln");
            }
          }
          --從Moon類派生出來的另一個字類,提供println方法的另一種實現方式
          package com.moonsoft.design;
          public class Moon2 extends Moon {
             public void println(){
              System.out.println("I am moon2!");
            }
          }
          --調用
           Moon moon = Moon.newInstance("com.moonsoft.design.Moon1");
           moon.println();
           或
           Moon moon = Moon.newInstance("com.moonsoft.design.Moon2");
           moon.println();

          posted @ 2006-01-04 16:41 月亮 閱讀(101) | 評論 (0)編輯 收藏

          JSP標簽的使用方法


          如要在JSP頁面上有一個鏈接,Url值是通過參數輸入的,用JSP標簽的實現步驟(當然實際中不會用標簽來完成這么簡單的功能):

          <一>.先從javax.servlet.jsp.tagext.BodyTagSupport派生一個新的類,并重載它的doStartTag()方法.如果是想要傳入參數的話,則還要在Bean中加入想要的變量,如這里要傳入一個url值,所以添加一個參數:linkUrl. 最后代碼如下:

          package com.moonsoft.jsptag;
          import javax.servlet.jsp.tagext.BodyTagSupport;
          import javax.servlet.jsp.JspTagException;
          import javax.servlet.jsp.JspException;
          public class UrlLinkTag extends BodyTagSupport  {
            private String linkUrl;
            public UrlLinkTag() {
            }
            public String getLinkUrl() {
              return linkUrl;
            }
            public void setLinkUrl(String linkUrl) {
              this.linkUrl = linkUrl;
            }
            public int doStartTag() throws JspException{
              try {
                this.pageContext
                    .getOut().print("<a href=\'"+linkUrl+"\' >"+linkUrl+"</a>");
              }
              catch (Exception ex) {
                ex.printStackTrace();
              }
              return 0;
            }
          }

          <二>新建一個tld文件,內容如下:
          <?xml version="1.0" encoding="ISO-8859-1"?>
          <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
           " <taglib>
                  <tlibversion>1.0</tlibversion>
           <jspversion>1.1</jspversion>
           <shortname>buttons</shortname>
           <uri>http://www.borland.com/jbuilder/internetbeans.tld</uri>
           <info>
           JSP tag extensions for InternetBeans Express
            </info>
              <tag>
           <name>urllink</name>
           <tagclass>com.moonsoft.jsptag.UrlLinkTag</tagclass>
           <bodycontent>jsp</bodycontent>
           <attribute>
            <name>linkUrl</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
           </attribute>
              </tag>
             </taglib>
            
          <三>在web.xml中引入這個taglib,在其中加入:

          <taglib>
              <taglib-uri>/moon</taglib-uri>
              <taglib-location>/WEB-INF/classes/com/moonsoft/jsptag/UrlLinkTag.tld</taglib-location>
          </taglib>


          <四>在jsp中引入這個標簽
          <%@ taglib uri="/moon" prefix="mylinkurl" %>
          這里uri是和web.xml中配置的taglib-uri對應的,prefix值只是在本jsp頁面作為標示用.

          下面就可以在jsp中使用這個標簽了:

          <mylinkurl:urllink linkUrl="

          這里面的mylinkurl為在本jsp頁面中設置的prefix值,urllink為tld文件中tag name,linkUrl為輸入的參數

          這樣就在jsp頁面上加入了一個:
          <a >http://www.baidu.com</a>鏈接

          posted @ 2005-12-29 13:47 月亮 閱讀(1430) | 評論 (0)編輯 收藏

          Java Excel 使用攻略

           現在正在做的項目中涉及大量的Excel文件導出導入操作,都是使用Java Excel來操作。

          Java Excel是一開放源碼項目,通過它Java開發人員可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件。下面我寫了一個簡單的例子,展示基本的讀取,新建,更新(包括常見格式的設置:字體,顏色,背景,合并單元格),拷貝操作,有這些其實已經基本足夠應付大部分問題了。下面是例的源代碼:

          import java.io.*;
          import java.util.Date;

          import jxl.*;
          import jxl.format.Colour;
          import jxl.format.UnderlineStyle;
          import jxl.read.biff.BiffException;
          import jxl.write.*;
          import jxl.format.UnderlineStyle;
          import jxl.format.CellFormat;;

          public class OperateExcel {
           
           /**
            * Read data from a excel file
            */
           public static void  readExcel(String excelFileName){
            Workbook  rwb = null;  
            try{
             InputStream stream = new FileInputStream(excelFileName);
             rwb = Workbook.getWorkbook(stream);
             Sheet  sheet = rwb.getSheet(0);
             Cell   cell  = null;
             int columns = sheet.getColumns();
             int rows    = sheet.getRows();
             for( int i=0 ; i< rows ; i++ )
              for( int j=0 ; j< columns ; j++){
               //attention: The first parameter is column,the second parameter is row.  
               cell = sheet.getCell(j,i);    
               String str00 = cell.getContents();
               if( cell.getType() == CellType.LABEL )
                 str00 += " LAEBL";
               else if( cell.getType() == CellType.NUMBER)
                 str00 += " number";
               else if( cell.getType() == CellType.DATE)
                 str00 += " date"; 
               System.out.println("00==>"+str00);
              } 
             stream.close();
            }
            catch(IOException e){  
             e.printStackTrace();
            }
            catch(BiffException e){
             e.printStackTrace();
            } 
            finally{  
             rwb.close();
            }
           }
           /**
            * create a new excelFile
            * @param excelFileName create name
            */
           public static void createExcelFile(String excelFileName){
            try{
             WritableWorkbook wwb = Workbook.createWorkbook(new File(excelFileName));
             WritableSheet     ws  = wwb.createSheet("sheet1",0);
             //also,The first parameter is  column,the second parameter is row.
             // add normal label data
             Label label00 = new Label(0,0,"Label00");
             ws.addCell(label00);
             //add font formating data   
             WritableFont  wf = new WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD , true);
             WritableCellFormat wff = new WritableCellFormat(wf);
             Label label10 = new Label(1,0,"Label10",wff);
             ws.addCell(label10);
             //add color font formating data
             WritableFont wf_color = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.DOUBLE_ACCOUNTING,Colour.RED);
             WritableCellFormat wff_color = new WritableCellFormat(wf_color);
             wff_color.setBackground(Colour.GRAY_25); //set background coloe to gray  
             Label label20 = new Label(2,0,"Label20",wff_color);   
             ws.addCell(label20);
             
             //合并單元格
             WritableFont wf_merge = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.DOUBLE_ACCOUNTING,Colour.GREEN);
             WritableCellFormat wff_merge = new WritableCellFormat(wf_merge);
             wff_merge.setBackground(Colour.BLACK);
             Label label30 = new Label(3,0,"Label30",wff_merge);   
             ws.addCell(label30);
             Label label40 = new Label(4,0,"Label40");
             ws.addCell(label40);
             Label label50 = new Label(5,0,"Label50");
             ws.addCell(label50);
               //合并 (0,3) (4,0)
               //attention : 如果合并后面的列不為空,那么就把后面格的內容清空,格式也是按前一個單元格的格式
             ws.mergeCells(3,0,4,0);
             
             //添加Number格式數據
             jxl.write.Number labelN = new jxl.write.Number(0, 1, 3.1415926);
             ws.addCell(labelN);
             
             //添加帶有formatting的Number對象
             jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
             jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
             jxl.write.Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN);
             ws.addCell(labelNF);
             
             //添加Boolean對象
             jxl.write.Boolean labelBoolean = new jxl.write.Boolean(2,1,false);
             ws.addCell(labelBoolean);
             
             //添加DateTime對象
             DateTime labelDT = new DateTime(3,1,new Date());
             ws.addCell(labelDT);
             
             //添加帶有格式的DataTime數據
             DateFormat dtf = new DateFormat("yyyy-MM-dd hh:mm:ss");
             WritableCellFormat wcfDt = new WritableCellFormat(dtf);   
             wcfDt.setBackground(Colour.YELLOW);
             DateTime labelDT_format =  new DateTime(4,1,new java.util.Date(),wcfDt);
             ws.addCell(labelDT_format);
             ws.mergeCells(4,1,5,1); //比較長,用兩列來顯示     
             
             wwb.write();
             wwb.close();
            }
            catch(IOException e){
             e.printStackTrace();
            }
            catch(WriteException e){
             e.printStackTrace();
            }  
           }
           /**
            * 如何更新Excel文件
            * @param fileName
            */
           public static void updateExcel(String fileName){  
            try{
             jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(fileName));
             WritableWorkbook wwb = Workbook.createWorkbook(new File(fileName),rw);
             //這里其實執行的是一次copy操作,把文件先讀到內存中,修改后再保存覆蓋原來的文件來實現update操作
             WritableSheet ws  = wwb.getSheet(0);
             WritableCell wc = ws.getWritableCell(0,0);
             if( wc.getType() == CellType.LABEL){
              Label l = (Label)wc;
              l.setString(wc.getContents()+"_new");
             }
             wwb.write();
             wwb.close();
            }
            catch(IOException e){
             e.printStackTrace();
            }
            catch(WriteException e){
             e.printStackTrace();
            } 
            catch(BiffException e){
             e.printStackTrace();
            }
           }
           /**
            * 如何copy Excel文件
            * @param fileName
            */
           public static void copyExcel(String sourFileName,String destFileName){  
            try{
             jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(sourFileName));
             WritableWorkbook wwb = Workbook.createWorkbook(new File(destFileName),rw);
             wwb.write();
             wwb.close();
            }
            catch(IOException e){
             e.printStackTrace();
            }
            catch(WriteException e){
             e.printStackTrace();
            } 
            catch(BiffException e){
             e.printStackTrace();
            }
           }
           
           public static void main(String [] argv){
            //OperateExcel.readExcel("E:\\test.xls");
            //OperateExcel.createExcelFile("E:\\test1.xls");
            //OperateExcel.updateExcel("E:\\test.xls");
            OperateExcel.copyExcel("E:\\test.xls","E:\\moon.xls");
           }

          }


          posted @ 2005-12-06 15:06 月亮 閱讀(2200) | 評論 (4)編輯 收藏

          執行過程中動態執行方法

          在編程中可能回碰到一些到實際運行時才指定要調用的方法的需要,最典型的是Struct的DispatchAction類,
          它能根據用戶頁面請求參數的不同來調用不同的方法來處理用戶請求。我下面寫了一個簡單的例子來簡單演示其
          實現方法:

          package learn;
          import java.lang.NoSuchMethodException;
          import java.lang.reflect.Method;
          import java.util.Date;

          public class TestMethod{
              protected Class clazz = this.getClass();
              protected Class[] no_parameter = {};  //方法無參數
              protected Class[] string_parameter = {String.class}; //以String 為參數
              protected Class[] int_parameter = {int.class};  //以int為參數
              protected Class[] multi_parameter = {String.class,Date.class}; //多個參數,第一個為String,第二二個為Date   
             
              public void method1(){
                System.out.println("method1");
              }
             
              public void method2(String str){
                System.out.println("method2=>"+str);
              }
             
              public void method3(int i){
                System.out.println("method2=>"+i);
              }
             
              public void method4(String str,Date date){
                System.out.println("method4=>"+str+"==="+date.toLocaleString());
              }
             
              public void execute(String methodName,int type,java.util.List list) throws Exception{
                try {
                  Method  m = getMethod(methodName,type);
                  int size = (list != null )? list.size():0;
                  Object o [] = new Object[size];
                  for( int i =0 ; i< size ; i++ )
                    o[i] = list.get(i);  //準備參數
                  m.invoke(this,o);
                }
                catch (Exception ex) {
                  ex.printStackTrace();
                  throw new Exception(ex.getMessage());
                }
              }
             
              private Method getMethod(String name,int type)throws NoSuchMethodException{
                  Method m = null;
                  switch(type){
                    case 1:
                      m = clazz.getMethod(name,no_parameter);
                      break;
                    case 2:
                      m = clazz.getMethod(name,string_parameter);
                      break;
                    case 3:
                      m = clazz.getMethod(name,int_parameter);
                      break;
                    case 4:
                      m = clazz.getMethod(name,multi_parameter);
                      break;
                    default:
                      m = clazz.getMethod(name,no_parameter);
                  }
                  return m;
              }
             
              public static void main(String [] argv){
                TestMethod testMethod = new TestMethod();
                try{
                  java.util.List list = new java.util.ArrayList();
                  testMethod.execute("method1", 1, list);
                  list.add("
          http://www.aygfsteel.com/minmoon");
                  testMethod.execute("method2", 2, list);
                  list.clear();
                  list.add("
          mailTo:xiaoliang@aspire-tech.com");
                  list.add(new Date());
                  testMethod.execute("method4",4,list);
                }
                catch(Exception e){
                  e.printStackTrace();
                }
              }
          }

          其中幾個關鍵的地方說明一下:
            clazz.getMethod(name,multi_parameter);  其中multi_parameter是要根據實際方法的參數來定義的。
            m.invoke(this,o);   o是要傳入方法的參數列表。

          posted @ 2005-11-23 00:18 月亮 閱讀(485) | 評論 (0)編輯 收藏

          23種面向對象的設計模式----Prototype模式


          原型模式定義:
          用原型實例指定創建對象的種類,并且通過拷貝這些原型創建新的對象.

          Prototype模式允許一個對象再創建另外一個可定制的對象,根本無需知道任何如何創建的細節,工作原理是:通過將一個原型對象傳給那個要發動創建的對象,這個要發動創建的對象通過請求原型對象拷貝它們自己來實施創建。

          如何使用?
          因為Java中的提供clone()方法來實現對象的克隆,所以Prototype模式實現一下子變得很簡單.

          以勺子為例:

          public abstract class AbstractSpoon implements Cloneable
          {
            String spoonName;

            public void setSpoonName(String spoonName) {this.spoonName = spoonName;}
            public String getSpoonName() {return this.spoonName;}

            public Object clone()
            {
              Object object = null;
              try {
                object = super.clone();
              } catch (CloneNotSupportedException exception) {
                System.err.println("AbstractSpoon is not Cloneable");
              }
              return object;
            }
          }

          有個具體實現(ConcretePrototype):

          public class SoupSpoon extends AbstractSpoon
          {
            public SoupSpoon()
            {
              setSpoonName("Soup Spoon");
            }
          }

          調用Prototype模式很簡單:

          AbstractSpoon spoon = new SoupSpoon();
          AbstractSpoon spoon2 = spoon.clone();

          當然也可以結合工廠模式來創建AbstractSpoon實例。

          在Java中Prototype模式變成clone()方法的使用,由于Java的純潔的面向對象特性,使得在Java中使用設計模式變得很自然,兩者已經幾乎是渾然一體了。這反映在很多模式上,如Interator遍歷模式。



          原文出處:http://www.jdon.com/designpatterns/prototype.htm

          看看寫的很好,就拿來引用一下,不用自己寫的那么累^_^.

          posted @ 2005-11-20 20:32 月亮 閱讀(204) | 評論 (0)編輯 收藏

          23種面向對象的設計模式----Factory method模式


          Factory method,工廠方法模式,定義一個用于創建對象的接口,讓字類決定實例化哪一個類。也就是使一個類的實例化延遲到其子類,提供一種方法使對象創建變得多態。
          下面是我寫的一個例子,如有兩種工人,car worker和bus worker,所生成的產品分別是car 和 bus,我按照Factory method 的實現如下:


          --先定義car 和 bus 的父類,都是一種產品
          package Factory;
          public class Product {
           
           public  void whoami(){
            System.out.println("I am a product!");
           }
          }

          --Car 類
          package Factory;
          public class Car extends Product { 
           public Car() {
           } 
           public void whoami(){
            System.out.println("I am a car!");
           } 
          }
          --Bus 類
          package Factory;
          public class Bus extends Product { 
           public Bus() {
           } 
           public void whoami(){
            System.out.println("I am a bus!");
           }
          }
          --定義CarWorker和BusWorker的父類 worker
          package Factory;
          public abstract class Worker { 
           private Product theProduct;
           public abstract Product  createProduct(); 
           public void work(){
            theProduct = createProduct();
           }
           public void showMessage(){
            this.theProduct.whoami();
           }
          }
          --Carworker
          package Factory;
          public class CarWorker extends Worker { 
           public Product createProduct(){
             return new Car();
           }
          }
          --BusWorker
          package Factory;
          public class BusWorker extends Worker { 
           public Product  createProduct(){
            return new Bus();
           }
          }
          --下面看看具體的調用
          package Factory;
          public class TestAll {

           public static void main(String [] argv){ 
            Worker  worker = new CarWorker();
            worker.work();
            worker.showMessage();
            
            Worker  worker1 = new BusWorker();
            worker1.work();
            worker1.showMessage(); 
           } 
          }
          可以看到雖然這樣實現有一些麻煩,如新加一種產品時,就必須從Product類創建一個子類,但是這樣做的
          好處也是顯而易見的,會給你系統帶來更大的可擴展性和盡量少的修改量,再添加一種產品一種工人的時候,對以前的代碼是不必做任何修改的。

          <個人觀點,僅作參考>

           

          posted @ 2005-11-13 21:35 月亮 閱讀(924) | 評論 (1)編輯 收藏

          23種面向對象的設計模式----Singleton模式

            Singleton模式為單態模式或者叫孤子模式,保證一個類只有一個實例,并提供一個訪問它的全局訪問點。
            Singleton模式的使用范圍比較廣泛,對于一些類來說,只有一個實例是很重要的。比如,你要論壇中

          的帖子計數器,每次瀏覽一次需要計數,單態類能否保持住這個計數,并且能synchronize的安全自動加

          1,如果你要把這個數字永久保存到數據庫,你可以在不修改單態接口的情況下方便的做到。
          下面是一個簡單的示例程序:
          package Singleton;
          public class TestSingleton { 
           private static TestSingleton  testSingleton = null;
           protected int  count = 0; 
           public static synchronized  TestSingleton getInstance(){
             if( testSingleton ==   null)
              testSingleton = new TestSingleton();
             return testSingleton;
           }
           public void addCount(){
            count ++;
           }
           public void showCount(){
            System.out.println("count :"+count);
           }  
          }
          我們還可以在這個基礎上做一個擴展,如從上面例子中的TestSingleton類擴展出多個子類,在

          getInstance方法中控制要使用的是哪個子類,具體實現代碼如下:

          -----TestSingleton.java
          package Singleton;
          public class TestSingleton { 
           private static TestSingleton  testSingleton = null;
           protected int  count = 0; 
           public static synchronized  TestSingleton getInstance(){
             if( testSingleton ==   null)
              testSingleton = new SubTestSingleton ();
             return testSingleton;
           }
           public void addCount(){
            count ++;
           }
           public void showCount(){
            System.out.println("TestSingleton count :"+count);
           }  
          }

          -----SubTestSingleton.java
          public class SubTestSingleton extends TestSingleton{
           public void showCount(){
            System.out.println("SubTestSingleton count :"+count);
           }
          }

          <以上為個人見解,歡迎大家評論!>

          posted @ 2005-11-13 15:54 月亮 閱讀(664) | 評論 (0)編輯 收藏

          面向對象的23種設計模式

            最近對面向對象的設計的23種經典的設計模式做了一個研究,接下來的Blog中我會按我的理解做個簡單介紹并提供我寫的示例代碼,歡迎大家的評論,共同提高.
            
             

          posted @ 2005-11-13 15:40 月亮 閱讀(756) | 評論 (0)編輯 收藏

          僅列出標題
          共4頁: 上一頁 1 2 3 4 下一頁 
          主站蜘蛛池模板: 德格县| 宿州市| 和平区| 湘阴县| 洪洞县| 涡阳县| 乌拉特前旗| 遵化市| 房山区| 广宗县| 理塘县| 吉安市| 柳林县| 阆中市| 克东县| 尼勒克县| 洛隆县| 博兴县| 石城县| 东乡族自治县| 古浪县| 五莲县| 札达县| 双鸭山市| 临沧市| 南充市| 正宁县| 南木林县| 巴马| 额济纳旗| 六枝特区| 华宁县| 黎平县| 桂平市| 綦江县| 临颍县| 河曲县| 武安市| 沁阳市| 漳浦县| 大名县|