隨筆 - 40, 文章 - 0, 評(píng)論 - 20, 引用 - 0
          數(shù)據(jù)加載中……

          Ibatis示例


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

          2.先新建一個(gè)xml文件 SqlMap.xml,在這個(gè)文件中定義使用了哪些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.定義一個(gè)公共類來生成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.至此就建立了一個(gè)簡單的ibatis示例.

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

          通過weblogic的數(shù)據(jù)源獲得數(shù)據(jù)庫連接的方法

          通過weblogic的數(shù)據(jù)源獲得數(shù)據(jù)庫連接的方法:

          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("查詢到空數(shù)據(jù)源!");
                }
                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 月亮 閱讀(1245) | 評(píng)論 (0)編輯 收藏

          一個(gè)設(shè)計(jì)中使用比較多的模式

          如果是在需求還沒確定或者是在兩個(gè)類實(shí)現(xiàn)相近功能時(shí)候,會(huì)大量使用下面的方式:
          --抽象類,注意其中的newInstance方法的實(shí)現(xiàn)
          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類派生出來的一個(gè)字類,提供println方法的一種實(shí)現(xiàn)方式
          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類派生出來的另一個(gè)字類,提供println方法的另一種實(shí)現(xiàn)方式
          package com.moonsoft.design;
          public class Moon2 extends Moon {
             public void println(){
              System.out.println("I am moon2!");
            }
          }
          --調(diào)用
           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 月亮 閱讀(102) | 評(píng)論 (0)編輯 收藏

          JSP標(biāo)簽的使用方法


          如要在JSP頁面上有一個(gè)鏈接,Url值是通過參數(shù)輸入的,用JSP標(biāo)簽的實(shí)現(xiàn)步驟(當(dāng)然實(shí)際中不會(huì)用標(biāo)簽來完成這么簡單的功能):

          <一>.先從javax.servlet.jsp.tagext.BodyTagSupport派生一個(gè)新的類,并重載它的doStartTag()方法.如果是想要傳入?yún)?shù)的話,則還要在Bean中加入想要的變量,如這里要傳入一個(gè)url值,所以添加一個(gè)參數(shù):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;
            }
          }

          <二>新建一個(gè)tld文件,內(nèi)容如下:
          <?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中引入這個(gè)taglib,在其中加入:

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


          <四>在jsp中引入這個(gè)標(biāo)簽
          <%@ taglib uri="/moon" prefix="mylinkurl" %>
          這里uri是和web.xml中配置的taglib-uri對(duì)應(yīng)的,prefix值只是在本jsp頁面作為標(biāo)示用.

          下面就可以在jsp中使用這個(gè)標(biāo)簽了:

          <mylinkurl:urllink linkUrl="

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

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

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

          Java Excel 使用攻略

           現(xiàn)在正在做的項(xiàng)目中涉及大量的Excel文件導(dǎo)出導(dǎo)入操作,都是使用Java Excel來操作。

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

          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 : 如果合并后面的列不為空,那么就把后面格的內(nèi)容清空,格式也是按前一個(gè)單元格的格式
             ws.mergeCells(3,0,4,0);
             
             //添加Number格式數(shù)據(jù)
             jxl.write.Number labelN = new jxl.write.Number(0, 1, 3.1415926);
             ws.addCell(labelN);
             
             //添加帶有formatting的Number對(duì)象
             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對(duì)象
             jxl.write.Boolean labelBoolean = new jxl.write.Boolean(2,1,false);
             ws.addCell(labelBoolean);
             
             //添加DateTime對(duì)象
             DateTime labelDT = new DateTime(3,1,new Date());
             ws.addCell(labelDT);
             
             //添加帶有格式的DataTime數(shù)據(jù)
             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);
             //這里其實(shí)執(zhí)行的是一次copy操作,把文件先讀到內(nèi)存中,修改后再保存覆蓋原來的文件來實(shí)現(xiàn)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 月亮 閱讀(2204) | 評(píng)論 (4)編輯 收藏

          執(zhí)行過程中動(dòng)態(tài)執(zhí)行方法

          在編程中可能回碰到一些到實(shí)際運(yùn)行時(shí)才指定要調(diào)用的方法的需要,最典型的是Struct的DispatchAction類,
          它能根據(jù)用戶頁面請(qǐng)求參數(shù)的不同來調(diào)用不同的方法來處理用戶請(qǐng)求。我下面寫了一個(gè)簡單的例子來簡單演示其
          實(shí)現(xiàn)方法:

          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 = {};  //方法無參數(shù)
              protected Class[] string_parameter = {String.class}; //以String 為參數(shù)
              protected Class[] int_parameter = {int.class};  //以int為參數(shù)
              protected Class[] multi_parameter = {String.class,Date.class}; //多個(gè)參數(shù),第一個(gè)為String,第二二個(gè)為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);  //準(zhǔn)備參數(shù)
                  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();
                }
              }
          }

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

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

          23種面向?qū)ο蟮脑O(shè)計(jì)模式----Prototype模式


          原型模式定義:
          用原型實(shí)例指定創(chuàng)建對(duì)象的種類,并且通過拷貝這些原型創(chuàng)建新的對(duì)象.

          Prototype模式允許一個(gè)對(duì)象再創(chuàng)建另外一個(gè)可定制的對(duì)象,根本無需知道任何如何創(chuàng)建的細(xì)節(jié),工作原理是:通過將一個(gè)原型對(duì)象傳給那個(gè)要發(fā)動(dòng)創(chuàng)建的對(duì)象,這個(gè)要發(fā)動(dòng)創(chuàng)建的對(duì)象通過請(qǐng)求原型對(duì)象拷貝它們自己來實(shí)施創(chuàng)建。

          如何使用?
          因?yàn)镴ava中的提供clone()方法來實(shí)現(xiàn)對(duì)象的克隆,所以Prototype模式實(shí)現(xiàn)一下子變得很簡單.

          以勺子為例:

          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;
            }
          }

          有個(gè)具體實(shí)現(xiàn)(ConcretePrototype):

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

          調(diào)用Prototype模式很簡單:

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

          當(dāng)然也可以結(jié)合工廠模式來創(chuàng)建AbstractSpoon實(shí)例。

          在Java中Prototype模式變成clone()方法的使用,由于Java的純潔的面向?qū)ο筇匦裕沟迷贘ava中使用設(shè)計(jì)模式變得很自然,兩者已經(jīng)幾乎是渾然一體了。這反映在很多模式上,如Interator遍歷模式。



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

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

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

          23種面向?qū)ο蟮脑O(shè)計(jì)模式----Factory method模式


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


          --先定義car 和 bus 的父類,都是一種產(chǎn)品
          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();
           }
          }
          --下面看看具體的調(diào)用
          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(); 
           } 
          }
          可以看到雖然這樣實(shí)現(xiàn)有一些麻煩,如新加一種產(chǎn)品時(shí),就必須從Product類創(chuàng)建一個(gè)子類,但是這樣做的
          好處也是顯而易見的,會(huì)給你系統(tǒng)帶來更大的可擴(kuò)展性和盡量少的修改量,再添加一種產(chǎn)品一種工人的時(shí)候,對(duì)以前的代碼是不必做任何修改的。

          <個(gè)人觀點(diǎn),僅作參考>

           

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

          23種面向?qū)ο蟮脑O(shè)計(jì)模式----Singleton模式

            Singleton模式為單態(tài)模式或者叫孤子模式,保證一個(gè)類只有一個(gè)實(shí)例,并提供一個(gè)訪問它的全局訪問點(diǎn)。
            Singleton模式的使用范圍比較廣泛,對(duì)于一些類來說,只有一個(gè)實(shí)例是很重要的。比如,你要論壇中

          的帖子計(jì)數(shù)器,每次瀏覽一次需要計(jì)數(shù),單態(tài)類能否保持住這個(gè)計(jì)數(shù),并且能synchronize的安全自動(dòng)加

          1,如果你要把這個(gè)數(shù)字永久保存到數(shù)據(jù)庫,你可以在不修改單態(tài)接口的情況下方便的做到。
          下面是一個(gè)簡單的示例程序:
          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);
           }  
          }
          我們還可以在這個(gè)基礎(chǔ)上做一個(gè)擴(kuò)展,如從上面例子中的TestSingleton類擴(kuò)展出多個(gè)子類,在

          getInstance方法中控制要使用的是哪個(gè)子類,具體實(shí)現(xiàn)代碼如下:

          -----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);
           }
          }

          <以上為個(gè)人見解,歡迎大家評(píng)論!>

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

          面向?qū)ο蟮?3種設(shè)計(jì)模式

            最近對(duì)面向?qū)ο蟮脑O(shè)計(jì)的23種經(jīng)典的設(shè)計(jì)模式做了一個(gè)研究,接下來的Blog中我會(huì)按我的理解做個(gè)簡單介紹并提供我寫的示例代碼,歡迎大家的評(píng)論,共同提高.
            
             

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

          僅列出標(biāo)題
          共4頁: 上一頁 1 2 3 4 下一頁 
          主站蜘蛛池模板: 临汾市| 乌鲁木齐市| 阿拉尔市| 阜新| 秀山| 涿州市| 醴陵市| 吉林省| 南丹县| 集安市| 南城县| 冷水江市| 通海县| 西乌| 泽州县| 海晏县| 佛坪县| 甘谷县| 那曲县| 宜宾市| 新安县| 博野县| 正安县| 炎陵县| 喀喇沁旗| 陕西省| 都江堰市| 固始县| 黑河市| 茶陵县| 涞源县| 宜兴市| 南宁市| 甘德县| 若羌县| 延庆县| 图们市| 思南县| 城口县| 色达县| 浏阳市|